Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0a25895ab | |||
| 05faa9e32d | |||
| 0dbd4064ac | |||
| 0f03da0a60 | |||
| 6d90ba8274 | |||
| 35894bf89e | |||
| 6394b1fe8c | |||
| d170c83b9e | |||
| 4a2d1d2d38 | |||
| 706f20e403 | |||
| 4d3362d93f | |||
| b03929174a | |||
| 7e2747ec73 | |||
| ae6be912e3 | |||
| 116bed16a8 | |||
| 063de7ee3e | |||
| 5c4ec562d0 | |||
| dbd481566c | |||
| 3f4571d3a7 | |||
| 8c1e7991cd | |||
| c1fdba510b | |||
| 435399dcf2 | |||
| ddaa0f4279 | |||
| b205967f1a | |||
| 7457315d6f | |||
| 59f9904d66 | |||
| 3b91a009ea | |||
| a6ae5aac31 | |||
| dc26b4d7e4 | |||
| bc6136d91e | |||
| 2e95841ca8 | |||
| a7c8127f90 | |||
| cad4e5c30e | |||
| 77647e4bb8 | |||
| 17c631aef2 | |||
| 89b5196676 | |||
| ab1d2f1683 | |||
| 1bcd88db32 | |||
| 63e613c061 | |||
| dbf59c544a | |||
| 14b9bf15f2 | |||
| 5dee2d87f5 | |||
| b71488097e | |||
| 6e92419cff | |||
| fdb3445bec | |||
| c1f5d96e25 | |||
| c874f7b797 | |||
| aefed5abd4 | |||
| 25c22b2ff5 | |||
| cb40c2438d | |||
| 2a76ec0fb8 | |||
| 57c8714889 | |||
| 8220f2060f | |||
| 41f2ea6e90 | |||
| 5082dd4fcf | |||
| cfbda4ca05 | |||
| 0218890a7a | |||
| a1ec688ec8 | |||
| 2529df4157 | |||
| a8f2b10956 | |||
| 3228e77c7f |
@@ -6,6 +6,10 @@ TELEGRAM_BOT_TOKEN=YOUR_BOT_TOKEN_HERE
|
||||
# Найти его можно в информации о боте у @BotFather.
|
||||
TELEGRAM_BOT_USERNAME=YOUR_BOT_USERNAME_HERE
|
||||
|
||||
# HTTPS URL Mini App dashboard, например: https://your-domain.example/miniapp
|
||||
# Используется ботом для кнопки меню Telegram и кнопки /start.
|
||||
TELEGRAM_MINI_APP_URL=
|
||||
|
||||
# Пароль для базы данных PostgreSQL
|
||||
POSTGRES_PASSWORD=StrongPasswordForDatabase
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ on:
|
||||
- main
|
||||
|
||||
env:
|
||||
VERSION: 1.4.0
|
||||
VERSION: 1.10.0
|
||||
|
||||
jobs:
|
||||
# ЧАСТЬ 1: Собираем образы и кладем в Gitea (чтобы делиться с ребятами)
|
||||
@@ -64,6 +64,7 @@ jobs:
|
||||
echo "TELEGRAM_BOT_TOKEN=${{ secrets.TELEGRAM_BOT_TOKEN }}" > .env
|
||||
echo "POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }}" >> .env
|
||||
echo "TELEGRAM_BOT_USERNAME=${{ secrets.TELEGRAM_BOT_USERNAME }}" >> .env
|
||||
echo "TELEGRAM_MINI_APP_URL=${{ secrets.TELEGRAM_MINI_APP_URL }}" >> .env
|
||||
|
||||
- name: Deploy Containers
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
name: PR Checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
test-and-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore
|
||||
|
||||
- name: Build Shared
|
||||
run: dotnet build src/GmRelay.Shared/GmRelay.Shared.csproj --no-restore
|
||||
|
||||
- name: Build Bot (compile check)
|
||||
run: dotnet build src/GmRelay.Bot/GmRelay.Bot.csproj --no-restore
|
||||
|
||||
- name: Build Web (compile check)
|
||||
run: dotnet build src/GmRelay.Web/GmRelay.Web.csproj --no-restore
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --verbosity normal
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,343 @@
|
||||
# Issue #15: Session Audit Log Implementation Plan
|
||||
|
||||
> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Add transparent audit history for every session change, visible to GM in Web Dashboard.
|
||||
|
||||
**Architecture:** PostgreSQL audit table + Dapper queries. Automatic logging inside mutating SessionService methods. New Razor page for GM history view.
|
||||
|
||||
**Tech Stack:** C# 12, Blazor SSR, Dapper, PostgreSQL, xUnit.
|
||||
|
||||
**Branch:** `issue-15-session-audit-log` (includes mobile UI bugfix cherry-pick)
|
||||
|
||||
**Version Bump:** `1.10.1` → `1.10.2`
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Database Migration (V013)
|
||||
|
||||
**Objective:** Create `session_audit_log` table.
|
||||
|
||||
**File:** Create `src/GmRelay.Bot/Migrations/V013__add_session_audit_log.sql`
|
||||
|
||||
```sql
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
CREATE TABLE session_audit_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
actor_telegram_id BIGINT NOT NULL,
|
||||
actor_name VARCHAR(255) NOT NULL,
|
||||
change_type VARCHAR(50) NOT NULL,
|
||||
CHECK (change_type IN ('Title','Time','Link','MaxPlayers','Status','WaitlistPromote','PlayerRemoved','BatchRescheduled','Cancelled')),
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX ix_session_audit_log_session_id ON session_audit_log(session_id);
|
||||
CREATE INDEX ix_session_audit_log_changed_at ON session_audit_log(changed_at);
|
||||
```
|
||||
|
||||
**Step 2:** Verify migration compiles: `psql $DATABASE_URL -f src/GmRelay.Bot/Migrations/V013__add_session_audit_log.sql` (optional, CI will test)
|
||||
|
||||
**Step 3:** Commit: `git add src/GmRelay.Bot/Migrations/V013__add_session_audit_log.sql && git commit -m "chore(#15): add session_audit_log migration"`
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Domain Model & Interface Methods
|
||||
|
||||
**Objective:** Add `SessionAuditLogEntry` record and two new methods to `ISessionStore`.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Services/ISessionStore.cs`
|
||||
- Modify: `src/GmRelay.Web/Services/SessionService.cs`
|
||||
|
||||
**Step 1: Add record to ISessionStore.cs** (after PlayerAttendanceStats)
|
||||
|
||||
```csharp
|
||||
public sealed record SessionAuditLogEntry(
|
||||
Guid Id,
|
||||
Guid SessionId,
|
||||
long ActorTelegramId,
|
||||
string ActorName,
|
||||
string ChangeType,
|
||||
string? OldValue,
|
||||
string? NewValue,
|
||||
DateTime ChangedAt
|
||||
);
|
||||
```
|
||||
|
||||
**Step 2: Add methods to ISessionStore interface**
|
||||
|
||||
```csharp
|
||||
Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue);
|
||||
Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId);
|
||||
```
|
||||
|
||||
**Step 3: Implement in SessionService.cs**
|
||||
|
||||
```csharp
|
||||
public async Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue)
|
||||
{
|
||||
using var connection = new NpgsqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"INSERT INTO session_audit_log (session_id, actor_telegram_id, actor_name, change_type, old_value, new_value) VALUES (@sessionId, @actorTelegramId, @actorName, @changeType, @oldValue, @newValue)",
|
||||
new { sessionId, actorTelegramId, actorName, changeType, oldValue, newValue });
|
||||
}
|
||||
|
||||
public async Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId)
|
||||
{
|
||||
using var connection = new NpgsqlConnection(connectionString);
|
||||
var entries = await connection.QueryAsync<SessionAuditLogEntry>(
|
||||
"SELECT id, session_id as SessionId, actor_telegram_id as ActorTelegramId, actor_name as ActorName, change_type as ChangeType, old_value as OldValue, new_value as NewValue, changed_at as ChangedAt FROM session_audit_log WHERE session_id = @sessionId ORDER BY changed_at DESC",
|
||||
new { sessionId });
|
||||
return entries.ToList();
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4:** Commit: `git add -A && git commit -m "feat(#15): add SessionAuditLogEntry and audit store methods"`
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Instrument Mutating Methods
|
||||
|
||||
**Objective:** Auto-log changes in key methods. Only log when value actually changes.
|
||||
|
||||
**File:** Modify `src/GmRelay.Web/Services/SessionService.cs`
|
||||
|
||||
**Step 1: Instrument UpdateSessionAsync**
|
||||
|
||||
Before executing UPDATE, read current session. After UPDATE, compare and log each changed field:
|
||||
|
||||
```csharp
|
||||
// After var currentSession = await GetSessionAsync(sessionId);
|
||||
// Before the UPDATE SQL:
|
||||
|
||||
if (currentSession is not null)
|
||||
{
|
||||
if (currentSession.Title != title)
|
||||
await LogSessionChangeAsync(sessionId, /* actor will be passed from caller */ ...);
|
||||
}
|
||||
```
|
||||
|
||||
**Problem:** SessionService doesn't know the actor (GM) telegram ID. Solution: add `long actorTelegramId` parameter to mutating methods, or use a decorator pattern.
|
||||
|
||||
**Better approach:** Instrument in `AuthorizedSessionService` which already has `gmId`. That is the authorized wrapper.
|
||||
|
||||
**Revised approach:** Add `IAuditLogger` interface and inject it. Or simpler: change `ISessionStore` mutating methods to accept `long actorTelegramId` and `string actorName` as last parameters.
|
||||
|
||||
**Simpler approach for this plan:** Since all mutating methods in `ISessionStore` are called through `AuthorizedSessionService`, instrument in `AuthorizedSessionService` methods AFTER the underlying `SessionService` call. BUT we need old values.
|
||||
|
||||
**Final approach:** Change `ISessionStore` methods to include `actorTelegramId` parameter, and inside `SessionService` fetch old values and log.
|
||||
|
||||
Let's add `long actorTelegramId` parameter to:
|
||||
- `UpdateSessionAsync`
|
||||
- `PromoteWaitlistedPlayerAsync`
|
||||
- `RemovePlayerFromSessionAsync`
|
||||
- `RescheduleBatchAsync`
|
||||
|
||||
Wait, this is a bigger change. Let's be more pragmatic: add a new `IAuditService` that can be called from `AuthorizedSessionService` after mutations. `IAuditService` just wraps `ISessionStore.LogSessionChangeAsync`.
|
||||
|
||||
Actually, simplest: add `actorTelegramId` and `actorName` parameters to `LogSessionChangeAsync` and call it from `AuthorizedSessionService` after each mutation. For old/new values, read the session before mutation in AuthorizedSessionService.
|
||||
|
||||
**Plan:**
|
||||
- `AuthorizedSessionService.UpdateSessionForGmAsync`: read session before update, call update, then log differences.
|
||||
- Same pattern for other mutating methods.
|
||||
|
||||
**Step 1: Read current session in AuthorizedSessionService.UpdateSessionForGmAsync**
|
||||
|
||||
```csharp
|
||||
public async Task UpdateSessionForGmAsync(Guid sessionId, long gmId, string title, DateTime scheduledAt, string joinLink, int? maxPlayers)
|
||||
{
|
||||
var groupId = await EnforceSessionOwnershipAsync(sessionId, gmId);
|
||||
var before = await store.GetSessionAsync(sessionId); // add this
|
||||
await store.UpdateSessionAsync(sessionId, groupId, title, scheduledAt, joinLink, maxPlayers);
|
||||
if (before is not null)
|
||||
{
|
||||
if (before.Title != title)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Title", before.Title, title);
|
||||
if (before.ScheduledAt != scheduledAt)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Time", before.ScheduledAt.ToString("O"), scheduledAt.ToString("O"));
|
||||
if (before.JoinLink != joinLink)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Link", before.JoinLink, joinLink);
|
||||
if (before.MaxPlayers != maxPlayers)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "MaxPlayers", before.MaxPlayers?.ToString(), maxPlayers?.ToString());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Wait, `EnforceSessionOwnershipAsync` returns `groupId` but we need it. Let me check the current AuthorizedSessionService code... We saw earlier it does `await EnforceSessionOwnershipAsync(sessionId, gmId)` then calls `store.UpdateSessionAsync`.
|
||||
|
||||
Actually, looking at the compact output from earlier, `AuthorizedSessionService` has `EnforceSessionOwnershipAsync` as a private helper. Let me verify.
|
||||
|
||||
From the compact output of AuthorizedSessionService earlier:
|
||||
```
|
||||
public async Task UpdateSessionForGmAsync(Guid sessionId, long gmId, string title, DateTime scheduledAt, string joinLink, int? maxPlayers)
|
||||
{
|
||||
var groupId = await EnforceSessionOwnershipAsync(sessionId, gmId);
|
||||
await store.UpdateSessionAsync(sessionId, groupId, title, scheduledAt, joinLink, maxPlayers);
|
||||
}
|
||||
```
|
||||
|
||||
So it DOES return groupId. Perfect.
|
||||
|
||||
But we need actor name. We can use the GM's display name from `GetGroupManagementForGmAsync` or just hardcode "ГМ" for now. Or we can query the player name. For simplicity, use "ГМ" + telegram ID, or query the player display name.
|
||||
|
||||
Actually, let's query the GM name from the group or just use telegram ID as identifier. Since this is audit log, having human-readable name is better. We can pass `actorName` to the log method.
|
||||
|
||||
Simpler: In `AuthorizedSessionService`, after `EnforceSessionOwnershipAsync`, we already know the group. We can get the GM name from group or just use a generic "ГМ" label. Actually, the telegram ID is sufficient for audit, and the display name can be resolved later in the UI.
|
||||
|
||||
Let's just log `actor_telegram_id` and use "ГМ" as actor_name. Or better, query the player display name if needed.
|
||||
|
||||
For this plan, let's keep it simple: log with `gmId` as actor_telegram_id and `"ГМ"` as actor_name. The UI can resolve the name.
|
||||
|
||||
**Step 2: Instrument all mutating AuthorizedSessionService methods**
|
||||
|
||||
Do this for:
|
||||
- `UpdateSessionForGmAsync` (Title, Time, Link, MaxPlayers)
|
||||
- `RescheduleBatchForGmAsync` (BatchRescheduled)
|
||||
- `PromoteWaitlistedPlayerForGmAsync` (WaitlistPromote)
|
||||
- `RemovePlayerFromSessionForGmAsync` (PlayerRemoved)
|
||||
- `UpdateBatchDetailsForGmAsync` (Title, Link)
|
||||
- `UpdateBatchNotificationModeForGmAsync` (maybe skip, internal)
|
||||
- `DeleteSessionHandler` in Bot features (Cancelled) — this is in Bot layer, not Web
|
||||
|
||||
For Cancelled status, we need to instrument `CancelSessionHandler` in Bot. But the Bot handlers don't use `ISessionStore` directly... they use `SessionService` or direct SQL. Let me check.
|
||||
|
||||
Actually, for this plan, focus on Web layer mutations first. Bot layer can be a follow-up.
|
||||
|
||||
**Step 3: Commit:** `git add -A && git commit -m "feat(#15): instrument audit logging in AuthorizedSessionService"`
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Web Page - SessionHistory.razor
|
||||
|
||||
**Objective:** GM-visible timeline of session changes.
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Web/Components/Pages/SessionHistory.razor`
|
||||
- Modify: `src/GmRelay.Web/Components/Pages/GroupDetails.razor` (add "История" link)
|
||||
- Modify: `src/GmRelay.Web/Components/Pages/EditSession.razor` (add "История" link)
|
||||
|
||||
**Step 1: Create SessionHistory.razor**
|
||||
|
||||
Route: `@page "/session/{SessionId:guid}/history"`
|
||||
|
||||
Layout: table with columns: Время, Актор, Тип изменения, Было, Стало.
|
||||
|
||||
Colors: use existing CSS variables.
|
||||
|
||||
**Step 2: Add navigation links**
|
||||
|
||||
In GroupDetails.razor sessions table: add 📜 История column/link.
|
||||
In EditSession.razor: add button "📜 История изменений" linking to `/session/{SessionId}/history`.
|
||||
|
||||
**Step 3: Commit:** `git add -A && git commit -m "feat(#15): add SessionHistory.razor page with audit timeline"`
|
||||
|
||||
---
|
||||
|
||||
## Task 5: FakeSessionStore + TDD Tests
|
||||
|
||||
**Objective:** Test audit logging. RED-GREEN-REFACTOR.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Web/AuthorizedSessionServiceTests.cs`
|
||||
|
||||
**Step 1: RED — Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public async Task UpdateSessionForGmAsync_LogsAudit_WhenTitleChanges()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var sessionId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups: [new(groupId, 42, "Alpha", gmId)],
|
||||
sessions: [new(sessionId, groupId, "Session A", DateTime.UtcNow, "Planned", "https://example.test/a", Guid.NewGuid(), 10, 42, 4, 1, 0)]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.UpdateSessionForGmAsync(sessionId, gmId, "Updated Title", DateTime.UtcNow.AddDays(1), "https://example.test/b", 5);
|
||||
|
||||
Assert.Single(store.LogEntries);
|
||||
Assert.Equal("Title", store.LogEntries[0].ChangeType);
|
||||
Assert.Equal("Session A", store.LogEntries[0].OldValue);
|
||||
Assert.Equal("Updated Title", store.LogEntries[0].NewValue);
|
||||
}
|
||||
```
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/Web/AuthorizedSessionServiceTests.cs --filter "FullyQualifiedName~LogsAudit" -v n`
|
||||
Expected: FAIL (FakeSessionStore doesn't have LogSessionChangeAsync / LogEntries)
|
||||
|
||||
**Step 2: GREEN — Add to FakeSessionStore**
|
||||
|
||||
Add `List<SessionAuditLogEntry> LogEntries` and implement `LogSessionChangeAsync` / `GetSessionHistoryAsync`.
|
||||
|
||||
**Step 3: Refactor — Add more tests**
|
||||
|
||||
- No audit when values unchanged
|
||||
- Audit for time change
|
||||
- Audit for link change
|
||||
- Audit for max players change
|
||||
- GetSessionHistoryAsync returns entries ordered by time desc
|
||||
|
||||
**Step 4: Full suite**
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj`
|
||||
Expected: all pass
|
||||
|
||||
**Step 5: Commit:** `git add -A && git commit -m "test(#15): add audit logging TDD tests"`
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Bump Version & Docs
|
||||
|
||||
**Objective:** Update version and documentation.
|
||||
|
||||
**Files:**
|
||||
- Modify: `Directory.Build.props`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `README.md`
|
||||
- Modify: Wiki «Руководство ГМа»
|
||||
|
||||
**Step 1: Bump version to 1.10.2**
|
||||
|
||||
**Step 2: Update README** — add "📜 История изменений сессии" bullet in Web Dashboard section.
|
||||
|
||||
**Step 3: Update wiki** — add subsection «Журнал действий» with description of how to access `/session/{id}/history`, what change types are tracked, and how to read the timeline.
|
||||
|
||||
**Step 4: Commit:** `git add -A && git commit -m "docs(#15): bump version to 1.10.2 and add audit log docs"`
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Push & PR
|
||||
|
||||
**Step 1:** `git push origin issue-15-session-audit-log`
|
||||
|
||||
**Step 2:** Create PR via `mcp_gitea_pull_request_write`
|
||||
|
||||
**Step 3:** Wait CI (`mcp_gitea_actions_run_read`)
|
||||
|
||||
**Step 4:** Merge PR
|
||||
|
||||
**Step 5:** Create tag `v1.10.2` and release
|
||||
|
||||
---
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] Migration V013 applied successfully
|
||||
- [ ] `SessionAuditLogEntry` record defined in `ISessionStore.cs`
|
||||
- [ ] `LogSessionChangeAsync` and `GetSessionHistoryAsync` implemented in `SessionService.cs`
|
||||
- [ ] `AuthorizedSessionService` logs on value changes only
|
||||
- [ ] `SessionHistory.razor` renders timeline for GM
|
||||
- [ ] Links from GroupDetails and EditSession pages
|
||||
- [ ] `FakeSessionStore` implements audit methods
|
||||
- [ ] TDD tests: RED → GREEN → all pass
|
||||
- [ ] Full `dotnet test` suite: all pass
|
||||
- [ ] Version bumped to 1.10.2
|
||||
- [ ] README and wiki updated
|
||||
- [ ] CI run success
|
||||
- [ ] PR merged to main
|
||||
- [ ] Tag `v1.10.2` created
|
||||
- [ ] Release published
|
||||
@@ -0,0 +1,480 @@
|
||||
# Issue #19: выровнять /newsession с batch-сценарием лендинга — Implementation Plan
|
||||
|
||||
> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Убедиться, что Telegram UX `/newsession` полностью соответствует batch-сценарию лендинга: мастер одной командой создаёт несколько дат, указывает лимит мест и ссылку, получает единую карточку с действиями. Обеспечить покрытие acceptance criteria регрессионными тестами и устранить найденные расхождения.
|
||||
|
||||
**Architecture:** Сценарий уже реализован в `CreateSessionHandler` + `NewSessionCommandParser` + `SessionBatchRenderer`. Основная задача — добавить недостающие тесты на «точный» landing-сценарий (несколько явных дат, не recurring), проверить отсутствие частичных сессий при любых ошибках, и убедиться, что карточка содержит все обещанные элементы.
|
||||
|
||||
**Tech Stack:** .NET 10, xUnit, Dapper, Npgsql, Telegram.Bot, Native AOT.
|
||||
|
||||
---
|
||||
|
||||
## Контекст кодовой базы
|
||||
|
||||
- `src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs` — создание batch, транзакция БД, отправка карточки.
|
||||
- `src/GmRelay.Bot/Features/Sessions/CreateSession/NewSessionCommandParser.cs` — парсинг команды: несколько `Время:`, `Мест:`, `Ссылка:`, `Картинка:`, recurring (`Игр:` + `Интервал:`).
|
||||
- `src/GmRelay.Shared/Rendering/SessionBatchRenderer.cs` — рендеринг HTML-карточки с кнопками.
|
||||
- `src/GmRelay.Shared/Rendering/BatchMessageEditor.cs` — редактирование batch-сообщения (text/photo).
|
||||
- `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs` — роутинг команд, текст `/help`.
|
||||
- `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/NewSessionCommandParserTests.cs` — тесты парсера.
|
||||
- `tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs` — smoke-тест всего landing-флоу через `FakeTelegramMessenger`.
|
||||
- `tests/GmRelay.Bot.Tests/Rendering/SessionBatchRendererTests.cs` — тесты рендерера.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: RED — тест landing-парсинга с несколькими явными датами
|
||||
|
||||
**Objective:** Проверить, что парсер корректно обрабатывает точный формат из лендинга: 2+ явных даты, лимит мест, ссылка, без recurring.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/NewSessionCommandParserTests.cs`
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Parse_ShouldHandleLandingBatchWithMultipleExplicitDates()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 4, 23, 12, 0, 0, TimeSpan.Zero);
|
||||
var text = """
|
||||
/newsession
|
||||
Название: Landing Batch Game
|
||||
Время: 15.05.2026 19:30
|
||||
Время: 22.05.2026 19:30
|
||||
Мест: 4
|
||||
Ссылка: https://example.test/landing
|
||||
""";
|
||||
|
||||
var result = NewSessionCommandParser.Parse(text, nowUtc);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal("Landing Batch Game", result.Title);
|
||||
Assert.Equal("https://example.test/landing", result.Link);
|
||||
Assert.Equal(4, result.MaxPlayers);
|
||||
Assert.Equal(2, result.ScheduledTimes.Count);
|
||||
Assert.Equal(new DateTimeOffset(2026, 5, 15, 16, 30, 0, TimeSpan.Zero), result.ScheduledTimes[0]);
|
||||
Assert.Equal(new DateTimeOffset(2026, 5, 22, 16, 30, 0, TimeSpan.Zero), result.ScheduledTimes[1]);
|
||||
Assert.Empty(result.PastTimeInputs);
|
||||
Assert.Empty(result.InvalidTimeInputs);
|
||||
Assert.Empty(result.InvalidSeatLimitInputs);
|
||||
Assert.Empty(result.InvalidRecurringInputs);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Parse_ShouldHandleLandingBatchWithMultipleExplicitDates" -v n`
|
||||
|
||||
Expected: PASS (функциональность уже реализована, но теста не было). Если FAIL — исправить парсер перед продолжением.
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/NewSessionCommandParserTests.cs
|
||||
git commit -m "test(#19): landing batch parser test with multiple explicit dates"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: RED — тест рендеринга landing-карточки
|
||||
|
||||
**Objective:** Проверить, что `SessionBatchRenderer` для landing-сценария выводит название, все даты, лимит, заполненность и кнопки записи/выхода.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Rendering/SessionBatchRendererTests.cs`
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Render_ShouldProduceLandingBatchCardWithAllRequiredElements()
|
||||
{
|
||||
var sessionId1 = Guid.NewGuid();
|
||||
var sessionId2 = Guid.NewGuid();
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(sessionId1, new DateTime(2026, 5, 15, 16, 30, 0, DateTimeKind.Utc), SessionStatus.Planned, 4),
|
||||
new SessionBatchDto(sessionId2, new DateTime(2026, 5, 22, 16, 30, 0, DateTimeKind.Utc), SessionStatus.Planned, 4)
|
||||
};
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(sessionId1, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(sessionId1, "Bob", null, ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(sessionId2, "Charlie", "charlie", ParticipantRegistrationStatus.Waitlisted)
|
||||
};
|
||||
|
||||
var result = SessionBatchRenderer.Render("Landing Batch Game", sessions, participants);
|
||||
var text = result.Text;
|
||||
var buttons = result.Markup.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
|
||||
Assert.Contains("Landing Batch Game", text);
|
||||
Assert.Contains("15 мая 2026, 19:30", text);
|
||||
Assert.Contains("22 мая 2026, 19:30", text);
|
||||
Assert.Contains("Места: 2/4", text);
|
||||
Assert.Contains("Места: 0/4", text);
|
||||
Assert.Contains("@alice", text);
|
||||
Assert.Contains("Bob", text);
|
||||
Assert.Contains("Лист ожидания (1)", text);
|
||||
Assert.Contains("@charlie", text);
|
||||
|
||||
Assert.Equal(4, buttons.Count);
|
||||
Assert.Contains($"join_session:{sessionId1}", buttons.Select(b => b.CallbackData));
|
||||
Assert.Contains($"leave_session:{sessionId1}", buttons.Select(b => b.CallbackData));
|
||||
Assert.Contains($"join_session:{sessionId2}", buttons.Select(b => b.CallbackData));
|
||||
Assert.Contains($"leave_session:{sessionId2}", buttons.Select(b => b.CallbackData));
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Render_ShouldProduceLandingBatchCardWithAllRequiredElements" -v n`
|
||||
|
||||
Expected: PASS (рендерер уже реализован, тест отсутствовал).
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Rendering/SessionBatchRendererTests.cs
|
||||
git commit -m "test(#19): landing batch renderer card elements test"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: RED — тест «ошибки ввода не создают частичных сессий»
|
||||
|
||||
**Objective:** Убедиться, что при невалидном вводе `CreateSessionHandler` не создаёт ни одной записи в БД и не публикует карточку.
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/CreateSessionHandlerTests.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs` (если найдена уязвимость)
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed class CreateSessionHandlerTests
|
||||
{
|
||||
// Примечание: полноценный интеграционный тест с реальной БД требует TestContainer.
|
||||
// Для Native AOT проекта используем подход с in-memory фейком через рефакторинг хендлера.
|
||||
// Ниже — тест-спецификация, которую реализуем через FakeDataSource или рефакторинг.
|
||||
}
|
||||
```
|
||||
|
||||
Поскольку `CreateSessionHandler` напрямую зависит от `NpgsqlDataSource` и `ITelegramBotClient`, для unit-тестирования нужно либо:
|
||||
а) использовать интеграционный тест с PostgreSQL (TestContainers), либо
|
||||
б) рефакторить хендлер, выделив `ISessionRepository`.
|
||||
|
||||
**Рекомендуемый подход (YAGNI):** добавить интеграционный тест в smoke-стиле через `FakeTelegramMessenger`, дополнив `TelegramLandingSmokeScenario` сценарием «invalid command does not publish anything».
|
||||
|
||||
**Step 1 (реализация):** Дописать тест в `TelegramLandingPromisesSmokeTests.cs`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Smoke_InvalidNewSession_ShouldNotPublishAnySessions()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 5, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
var invalidText = """
|
||||
/newsession
|
||||
Название: Bad Game
|
||||
Время: 01.01.2020 19:30
|
||||
"""; // нет ссылки
|
||||
|
||||
var parseResult = NewSessionCommandParser.Parse(invalidText, nowUtc);
|
||||
|
||||
Assert.False(parseResult.IsValid);
|
||||
Assert.Empty(parseResult.ScheduledTimes);
|
||||
// Убеждаемся, что smoke-сценарий не может быть опубликован
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
TelegramLandingSmokeScenario.Publish(parseResult, SessionNotificationMode.GroupAndDirect));
|
||||
}
|
||||
```
|
||||
|
||||
В `TelegramLandingSmokeScenario.Publish` добавить guard:
|
||||
```csharp
|
||||
if (!parseResult.IsValid)
|
||||
throw new InvalidOperationException("Cannot publish invalid parse result");
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Smoke_InvalidNewSession_ShouldNotPublishAnySessions" -v n`
|
||||
|
||||
Expected: FAIL — guard ещё не добавлен.
|
||||
|
||||
**Step 3: Write minimal implementation**
|
||||
|
||||
Добавить guard в `TelegramLandingSmokeScenario.Publish`:
|
||||
```csharp
|
||||
if (!parseResult.IsValid)
|
||||
throw new InvalidOperationException("Cannot publish invalid parse result");
|
||||
```
|
||||
|
||||
**Step 4: Run test to verify pass**
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs
|
||||
git add src/GmRelay.Bot/... # если были изменения
|
||||
# (файл CreateSessionHandler.cs не трогаем — валидация происходит ДО транзакции)
|
||||
git commit -m "test(#19): ensure invalid parse does not publish partial sessions"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: RED — тест atomicity при сбое отправки batch-сообщения
|
||||
|
||||
**Objective:** В `CreateSessionHandler` `batch_message_id` обновляется ПОСЛЕ `transaction.Commit()`. Если отправка сообщения в Telegram падает, сессии созданы, но `batch_message_id` не записан — игроки не увидят карточку. Нужно либо доказать, что это обработано, либо исправить.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs`
|
||||
|
||||
**Step 1: Анализ кода**
|
||||
|
||||
Текущий порядок в `CreateSessionHandler`:
|
||||
1. Валидация (до транзакции) ✓
|
||||
2. `BEGIN TRANSACTION`
|
||||
3. INSERT players, groups, sessions
|
||||
4. `COMMIT`
|
||||
5. `SessionBatchRenderer.Render`
|
||||
6. `botClient.SendMessage/SendPhoto`
|
||||
7. `UPDATE sessions SET batch_message_id = ...` (вне транзакции!)
|
||||
|
||||
Если шаг 6 падает — сессии «висят» без published message. Это частичное создание.
|
||||
|
||||
**Step 2: Write minimal fix**
|
||||
|
||||
Обернуть отправку сообщения и обновление `batch_message_id` в retry-loop с fallback. Если после N попыток не удалось — отправить GM уведомление об ошибке и оставить сессии (не удалять, чтобы не терять данные), но сделать так, чтобы `batch_message_id` обновлялся только при успешной отправке.
|
||||
|
||||
```csharp
|
||||
// Внутри CreateSessionHandler, после Commit:
|
||||
Message? batchMessage = null;
|
||||
var sendAttempts = 0;
|
||||
const int maxAttempts = 3;
|
||||
Exception? lastSendException = null;
|
||||
|
||||
while (batchMessage is null && sendAttempts < maxAttempts)
|
||||
{
|
||||
sendAttempts++;
|
||||
try
|
||||
{
|
||||
batchMessage = await SendBatchMessageAsync(...); // extracted method
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
lastSendException = ex;
|
||||
logger.LogWarning(ex, "Attempt {Attempt} failed to send batch message for {BatchId}", sendAttempts, batchId);
|
||||
if (sendAttempts < maxAttempts)
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (batchMessage is not null)
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE sessions SET batch_message_id = @MsgId WHERE batch_id = @BatchId",
|
||||
new { MsgId = batchMessage.MessageId, BatchId = batchId });
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogError(lastSendException, "Failed to send batch message for {BatchId} after {MaxAttempts} attempts", batchId, maxAttempts);
|
||||
await botClient.SendMessage(
|
||||
chatId,
|
||||
$"⚠️ Сессии созданы, но не удалось опубликовать карточку. Пожалуйста, используйте /listsessions.\n\nОшибка: {lastSendException?.Message}",
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3: Extract helper**
|
||||
|
||||
Выделить метод `SendBatchMessageAsync` из текущего inline-кода отправки (строки 117–176 в текущем файле), чтобы логика была читаемой и тестируемой.
|
||||
|
||||
**Step 4: Run tests**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ -v n`
|
||||
|
||||
Expected: все существующие тесты PASS, новая логика не ломает smoke-тест (т.к. smoke-тест не использует реальный `CreateSessionHandler`).
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs
|
||||
git commit -m "fix(#19): retry batch message send and prevent orphaned sessions without batch_message_id"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: RED — smoke-тест полного landing-сценария с явными датами
|
||||
|
||||
**Objective:** Дополнить `TelegramLandingPromisesSmokeTests` полным сквозным сценарием: парсинг → публикация → запись → выход → проверка карточки.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs`
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Smoke_LandingExplicitDatesBatch_ShouldSupportFullLifecycle()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 5, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
var text = """
|
||||
/newsession
|
||||
Название: Landing Explicit Batch
|
||||
Время: 15.05.2026 19:30
|
||||
Время: 22.05.2026 19:30
|
||||
Мест: 3
|
||||
Ссылка: https://example.test/explicit
|
||||
""";
|
||||
|
||||
var parseResult = NewSessionCommandParser.Parse(text, nowUtc);
|
||||
Assert.True(parseResult.IsValid);
|
||||
Assert.Equal(2, parseResult.ScheduledTimes.Count);
|
||||
Assert.Equal(3, parseResult.MaxPlayers);
|
||||
|
||||
var scenario = TelegramLandingSmokeScenario.Publish(parseResult, SessionNotificationMode.GroupAndDirect);
|
||||
Assert.Contains("Landing Explicit Batch", scenario.LastMessage.Text);
|
||||
Assert.Contains("15 мая 2026, 19:30", scenario.LastMessage.Text);
|
||||
Assert.Contains("22 мая 2026, 19:30", scenario.LastMessage.Text);
|
||||
Assert.Contains("Места: 0/3", scenario.LastMessage.Text);
|
||||
|
||||
var callbacks = CallbackData(scenario.LastMessage.Markup);
|
||||
Assert.Equal(4, callbacks.Count); // join+leave для каждой из 2 сессий
|
||||
|
||||
var firstSessionId = scenario.Sessions[0].Id;
|
||||
var alice = scenario.Join(firstSessionId, 1001, "Alice", "alice");
|
||||
var bob = scenario.Join(firstSessionId, 1002, "Bob", "bob");
|
||||
var carol = scenario.Join(firstSessionId, 1003, "Carol", "carol");
|
||||
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, alice));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, bob));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Waitlisted, scenario.RegistrationStatus(firstSessionId, carol));
|
||||
Assert.Contains("Места: 2/3", scenario.LastMessage.Text);
|
||||
Assert.Contains("@alice", scenario.LastMessage.Text);
|
||||
Assert.Contains("@bob", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
|
||||
scenario.Leave(firstSessionId, alice);
|
||||
Assert.False(scenario.HasParticipant(firstSessionId, alice));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, carol));
|
||||
Assert.DoesNotContain("@alice", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Smoke_LandingExplicitDatesBatch_ShouldSupportFullLifecycle" -v n`
|
||||
|
||||
Expected: PASS (функциональность уже существует, тест добавляет регрессионное покрытие).
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs
|
||||
git commit -m "test(#19): full lifecycle smoke test for explicit-dates landing batch"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Проверка и обновление `/help` текста
|
||||
|
||||
**Objective:** Убедиться, что текст `/help` точно отражает landing-формат и упоминает batch-сценарий.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs`
|
||||
|
||||
**Step 1: Read current `/help` text**
|
||||
|
||||
Текущий `/help` уже содержит:
|
||||
```
|
||||
/newsession
|
||||
Название: My Game
|
||||
Время: 15.05.2026 19:30
|
||||
Время: 22.05.2026 19:30
|
||||
Мест: 4
|
||||
Ссылка: https://link
|
||||
Картинка: https://cover
|
||||
|
||||
Для регулярного расписания можно указать одну дату:
|
||||
Игр: 4
|
||||
Интервал: 7
|
||||
```
|
||||
|
||||
**Step 2: Verify alignment**
|
||||
|
||||
- Формат совпадает с лендингом ✓
|
||||
- Упоминается `Мест:` ✓
|
||||
- Упоминается несколько `Время:` ✓
|
||||
- Упоминается `Ссылка:` ✓
|
||||
|
||||
Никаких изменений не требуется. Если тестировщик считает, что help недостаточно явно описывает batch-сценарий — добавить заголовок:
|
||||
```
|
||||
<b>Создать набор сессий (batch):</b>
|
||||
```
|
||||
|
||||
**Step 3: Commit (если изменения были)**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs
|
||||
git commit -m "docs(#19): clarify batch scenario in /help text"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Финальный прогон и cleanup
|
||||
|
||||
**Objective:** Убедиться, что все тесты проходят, нет warnings, и план соответствует acceptance criteria.
|
||||
|
||||
**Files:**
|
||||
- Все изменённые файлы
|
||||
|
||||
**Step 1: Run full test suite**
|
||||
|
||||
```bash
|
||||
dotnet test tests/GmRelay.Bot.Tests/ -v n
|
||||
```
|
||||
|
||||
Expected: все тесты PASS.
|
||||
|
||||
**Step 2: Verify checklist**
|
||||
|
||||
- [ ] `Parse_ShouldHandleLandingBatchWithMultipleExplicitDates` — PASS
|
||||
- [ ] `Render_ShouldProduceLandingBatchCardWithAllRequiredElements` — PASS
|
||||
- [ ] `Smoke_InvalidNewSession_ShouldNotPublishAnySessions` — PASS
|
||||
- [ ] `Smoke_LandingExplicitDatesBatch_ShouldSupportFullLifecycle` — PASS
|
||||
- [ ] Все существующие тесты — PASS
|
||||
- [ ] `CreateSessionHandler` обрабатывает сбой отправки batch-сообщения (retry + fallback)
|
||||
- [ ] `/help` текст соответствует landing-формату
|
||||
- [ ] Никаких новых warnings при сборке
|
||||
|
||||
**Step 3: Commit финальный**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "feat(#19): align /newsession with landing batch scenario — tests + atomicity fix"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria Verification
|
||||
|
||||
| Критерий | Статус | Покрытие |
|
||||
|---|---|---|
|
||||
| Мастер может создать batch из нескольких дат | ✅ Реализовано | Task 1, Task 5 |
|
||||
| Карточка содержит название, даты, лимит, заполненность, действия | ✅ Реализовано | Task 2, Task 5 |
|
||||
| Ошибки ввода не создают частичных сессий | ✅ Реализовано (валидация до транзакции) | Task 3 |
|
||||
| Сбой публикации карточки не оставляет «висячие» сессии без `batch_message_id` | 🔄 Фиксится | Task 4 |
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
Plan complete and saved to `.hermes/plans/gmrelay-issue-19.md`. Ready to execute using subagent-driven-development — dispatch a fresh subagent per task with two-stage review (spec compliance then code quality). Shall I proceed?
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>1.4.0</Version>
|
||||
<Version>1.10.2</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -4,155 +4,132 @@
|
||||
|
||||
Проект разработан с упором на производительность, архитектуру Vertical Slice, Native AOT (для бота) и удобство развертывания с использованием .NET Aspire.
|
||||
|
||||
**Текущая версия:** `v1.4.0`.
|
||||
**Текущая версия:** `v1.10.2`.
|
||||
|
||||
---
|
||||
|
||||
## ✨ Ключевые возможности
|
||||
## ✨ Key Features
|
||||
|
||||
### 🤖 Telegram Бот
|
||||
- **📅 Создание расписаний (Batch Sessions)**: Создавайте сразу несколько игр одним сообщением (на неделю или месяц вперед).
|
||||
### 🤖 Telegram Bot
|
||||
- **📅 Создание расписаний (Batch Sessions)**: Создавайте сразу несколько игр одним сообщением изменения (на недельный месяц в перед).
|
||||
- **🖼 Обложки расписаний**: И batch-посту можно прикрепить фото к `/newsession` или указать строку `Картинка: https://...`; бот отправит обложку перед сообщением записи.
|
||||
- **⚡ Быстрые повторы расписания**: Для регулярной кампании можно указать одну дату, количество игр и интервал, а бот сам развернёт повторяющийся batch.
|
||||
- **✋ Интерактивная запись и выход**: Игроки записываются на конкретные даты и самостоятельно снимают запись нажатием одной кнопки.
|
||||
- **👥 Лимит мест и лист ожидания**: ГМ задаёт максимальный состав, бот не переполняет сессию, автоматически ведёт очередь ожидания и освобождённое место отдаёт первому ожидающему.
|
||||
- **📁 Поддержка Форумов (Telegram Topics)**: Бот автоматически создает тему во вложенных чатах Telegram под каждую новую пачку игр.
|
||||
- **❌ Управление сессиями**: Мастер может отменять отдельные игры прямо в общем сообщении расписания.
|
||||
- **🗓 Экспорт в Календарь**: Генерация файла `.ics` для добавления всех игр в Google, Apple или Яндекс Календарь одной командой.
|
||||
- **🚀 Native AOT**: Скомпилирован в нативный бинарный файл. Мгновенный запуск и минимальное потребление памяти. Идеально для **Raspberry Pi**.
|
||||
|
||||
### 🌐 Web Dashboard (Blazor Server)
|
||||
- **🔐 Авторизация через Telegram**: Безопасный вход с использованием Telegram Login Widget (HMAC-SHA256 валидация).
|
||||
- **📝 Удобное редактирование**: Веб-интерфейс для детального редактирования сессий, изменения дат, названий и статусов.
|
||||
- **🧩 Bulk-операции для Batch Sessions**: ГМ может обновить общий title/link, перенести всю пачку на фиксированный шаг и клонировать batch на следующую неделю или месяц.
|
||||
- **❌ Управление сессиями**: Owner и назначенные co-GM могут создавать, отменять, удалять и переносить игры из Telegram через `/listsessions`; публичный пост записи показывает только кнопки игроков.
|
||||
- **🔄 Голосование за перенос**: Быстрый поиск свободного места с через свободное недель и кнопками новых времени и дедлайном.
|
||||
- **🔔 Уведомления**: Игрок получают за 24 часа, напоминание за 1 час, ссылку перед игрой, отмены и переносы; групповые уведомления при этом остаются.
|
||||
- **🕐 Режим уведомлений batch**: Для каждой пачки можно выбрать `В группе и в личку` или `Только в группе`.
|
||||
- **⬆️ Управление очередью**: Веб-интерфейс показывает заполненность, лист ожидания и позволяет ГМу поднять первого игрока из очереди.
|
||||
- **🔄 Автоматическая синхронизация**: Любые изменения в веб-интерфейсе мгновенно обновляют сообщения с расписанием в Telegram-чатах игроков.
|
||||
- **🕒 Управление временем**: UI адаптирован под московское время (UTC+3), в то время как база данных работает в UTC.
|
||||
|
||||
### 🌐 Web Dashboard (Blazor Server)
|
||||
- **🔐 Авторизация через Telegram**: Telegram Login Widget с HMAC-SHA256 валидацией.
|
||||
- **📱 Telegram Mini App Dashboard**: Мобильная панель открывается из Telegram, проверяет `initData` на сервере, учитывает safe-area телефона и верхнюю панель Telegram.
|
||||
- **✏️ Редактирование**: Детальное изменение дат, названий и статусов сессий.
|
||||
- **🤝 Co-GM и делегирование**: Owner назначает помощников по Telegram ID; co-GM управляет расписанием, но **не может назначать других co-GM**.
|
||||
- **📋 Шаблоны кампаний**: Вкладка `Шаблоны` отдельно от страницы группы: сохранение типовых параметров и запуск нового batch из шаблона.
|
||||
- **📦 Bulk-операции для Batch Sessions**:
|
||||
- обновить общий `title`/`link` у всей пачки;
|
||||
- перенести пачку на фиксированный шаг в днях;
|
||||
- клонировать batch на следующую неделю или месяц.
|
||||
- **⬆️ Управление очередью**: Заполненность, лист ожидания и ручное повышение игрока из очереди.
|
||||
- **📜 История изменений сессий**: Страница `/session/{id}/history` показывает аудит-лог всех значимых изменений (время, ссылка, название, участники, статус) с указанием акторов и дат.
|
||||
- **📊 Статистика посещаемости**: Страница `/group/{id}/stats` показывает долю присутствия, количество пропусков и среднюю явку по каждому игроку группы.
|
||||
- **🔄 Автосинхронизация**: Изменения в вебе мгновенно перерисовывают Telegram-сообщения расписания.
|
||||
|
||||
---
|
||||
|
||||
## 🛠 Технологический стек
|
||||
|
||||
- **Язык**: C# 14 (.NET 10)
|
||||
- **Архитектура**: Vertical Slice Architecture, общая библиотека (`GmRelay.Shared`) для доменной логики.
|
||||
- **Бот**: Telegram.Bot, Native AOT.
|
||||
- **Веб-интерфейс**: Blazor Server.
|
||||
- **Оркестрация**: .NET Aspire (`GmRelay.AppHost`).
|
||||
- **База данных**: PostgreSQL
|
||||
- **ORM**: Dapper (с использованием Dapper.AOT для source generators).
|
||||
- **Миграции**: DbUp.
|
||||
- **Развертывание**: Docker Compose + Multi-arch (AMD64/ARM64).
|
||||
| Компонент | Технология |
|
||||
|---|---|
|
||||
| Язык | C# 14 (.NET 10) |
|
||||
| Архитектура | Vertical Slice + общая библиотека `GmRelay.Shared` |
|
||||
| Бот | Telegram.Bot, **Native AOT** |
|
||||
| Веб | Blazor Server |
|
||||
| Оркестрация | .NET Aspire (`GmRelay.AppHost`) |
|
||||
| БД | PostgreSQL |
|
||||
| ORM | Dapper + **Dapper.AOT** (source generators) |
|
||||
| Миграции | DbUp |
|
||||
| Развёртывание | Docker Compose, Multi-arch (**AMD64/ARM64**) |
|
||||
|
||||
> [!NOTE]
|
||||
> При использовании Dapper в режиме Native AOT все SQL-запросы используют строго типизированные DTO; динамические типы (`dynamic`) не поддерживаются.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Быстрый старт (Docker Compose)
|
||||
|
||||
Проект использует Docker Compose для одновременного запуска базы данных, бота и веб-интерфейса.
|
||||
|
||||
### 1. Подготовка
|
||||
Убедитесь, что у вас установлены **Docker** и **Docker Compose**.
|
||||
|
||||
### 2. Настройка окружения
|
||||
Скопируйте файл-шаблон и заполните его значениями:
|
||||
**Требования:** Docker и Docker Compose.
|
||||
|
||||
### 1. Настройка окружения
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Отредактируйте `.env`:
|
||||
|
||||
**Ключевые переменные `.env`:**
|
||||
```env
|
||||
# Токен вашего бота от @BotFather (используется и для бота, и как секретный ключ для веб-авторизации)
|
||||
# Токен от @BotFather (используется ботом и как секретный ключ веб-авторизации)
|
||||
TELEGRAM_BOT_TOKEN=ваш_токен_здесь
|
||||
|
||||
# Имя вашего бота в Telegram (без @), например: GmRelayBot.
|
||||
# Найти его можно в информации о боте у @BotFather.
|
||||
# Используется для работы виджета авторизации (Telegram Login Widget).
|
||||
# Имя бота без @ (для Telegram Login Widget)
|
||||
TELEGRAM_BOT_USERNAME=ваше_имя_бота_здесь
|
||||
|
||||
# Пароль для базы данных PostgreSQL
|
||||
POSTGRES_PASSWORD=ваш_надежный_пароль
|
||||
# HTTPS URL Mini App, например https://your-domain.example/miniapp
|
||||
TELEGRAM_MINI_APP_URL=https://your-domain.example/miniapp
|
||||
|
||||
# Локальный порт веб-интерфейса GM-Relay
|
||||
POSTGRES_PASSWORD=ваш_надежный_пароль
|
||||
GMRELAY_WEB_PORT=8080
|
||||
```
|
||||
|
||||
*(Опционально)* Настройте домен Telegram бота в @BotFather командой `/setdomain` для работы виджета авторизации на вашем сайте.
|
||||
**Настройка в @BotFather:**
|
||||
- Команда `/setdomain` для работы виджета авторизации на вашем домене.
|
||||
- Для Mini App настройте домен Web Dashboard и menu button на URL из `TELEGRAM_MINI_APP_URL`.
|
||||
- Начиная с **v1.9.3** дополнительных действий для фикса входа не требуется: fallback выполняется внутри активного Telegram WebView по тому же HTTPS-адресу `/miniapp`.
|
||||
|
||||
### 3. Запуск
|
||||
Выполните команду:
|
||||
### 2. Запуск
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
Инфраструктура автоматически:
|
||||
- Создаст локальную Docker-сеть и volume PostgreSQL, если их ещё нет.
|
||||
- Поднимет PostgreSQL, доступный для контейнеров как `db:5432`.
|
||||
- Запустит бота (применив миграции БД).
|
||||
- Запустит веб-интерфейс на `http://localhost:8080` или другом порту из `GMRELAY_WEB_PORT`.
|
||||
|
||||
**Автоматически выполняется:**
|
||||
- создание Docker-сети и volume PostgreSQL;
|
||||
- подъём PostgreSQL (`db:5432`);
|
||||
- запуск бота с плавной миграцией (DbUp);
|
||||
- запуск веб-приложения с подключением к БД и Telegram API.
|
||||
|
||||
### 3. Первоначальная настройка
|
||||
1. Напишите боту `/start`.
|
||||
2. Создайте группу через `/newgroup`.
|
||||
3. Откройте Mini App или Web Dashboard для расширенного управления.
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Настройка бота в Telegram
|
||||
## 🗂 Структура репозитория
|
||||
|
||||
Чтобы бот работал корректно:
|
||||
1. **Добавьте бота в группу** (или Супергруппу/Форум).
|
||||
2. **Назначьте бота Администратором**.
|
||||
3. **Необходимые права**:
|
||||
* `Выбор тем` (Managed Topics) — **обязательно** для Форумов.
|
||||
* `Отправка сообщений`.
|
||||
* `Закрепление сообщений` — рекомендуется.
|
||||
|
||||
> [!TIP]
|
||||
> Колонку "Мастер" (GM) бот определяет по первому человеку, который создал сессию в этой группе. Только этот пользователь сможет отменять игры через кнопки бота и редактировать их в веб-интерфейсе.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Инструкция для Мастера
|
||||
|
||||
### Создание расписания игр
|
||||
Используйте команду `/newsession` с описанием в следующем формате:
|
||||
|
||||
```text
|
||||
/newsession
|
||||
Название: Легенды Берега Мечей (D&D 5e)
|
||||
Время: 15.05.2024 19:30
|
||||
Время: 22.05.2024 19:00
|
||||
Мест: 4
|
||||
Ссылка: https://discord.gg/invite-link
|
||||
```
|
||||
|
||||
Строка `Мест:` необязательна. Если она указана, игроки сверх лимита попадут в лист ожидания, а ГМ сможет повысить первого ожидающего через кнопку в Telegram или Web Dashboard.
|
||||
|
||||
Игрок может самостоятельно снять запись кнопкой `🚪 Выйти` в сообщении расписания. Если он был в основном составе и в листе ожидания есть игроки, бот автоматически переводит первого ожидающего в основной состав и обновляет сообщение пачки.
|
||||
|
||||
### Bulk-операции в Web Dashboard
|
||||
На странице группы Web Dashboard показывает отдельный блок для каждой пачки игр. ГМ может:
|
||||
- обновить общий `title` и `link` сразу у всех сессий batch;
|
||||
- перенести пачку, задав новую первую дату и фиксированный шаг между играми в днях;
|
||||
- клонировать batch на следующую неделю или следующий календарный месяц.
|
||||
|
||||
После редактирования или переноса исходное Telegram-сообщение расписания перерисовывается. При клонировании создаётся новая пачка с новым Telegram-сообщением и пустым составом игроков.
|
||||
|
||||
### Другие команды
|
||||
- `/listsessions` — Показать список всех актуальных игр в этой группе.
|
||||
- `/reschedulesession` — Перенести сессию на другое время с голосованием игроков.
|
||||
- `/deletesession` — Удалить сессию.
|
||||
- `/exportcalendar` — Получить `.ics` файл с играми.
|
||||
- `/help` — Справка по формату.
|
||||
|
||||
---
|
||||
|
||||
## 🏗 Разработка и запуск локально (.NET Aspire)
|
||||
|
||||
Для локальной разработки проще всего использовать .NET Aspire:
|
||||
|
||||
1. Установите [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) и workload Aspire.
|
||||
2. Откройте решение `GM-Relay.slnx`.
|
||||
3. Установите переменные окружения (или user secrets) для `GmRelay.AppHost`.
|
||||
4. Запустите проект `GmRelay.AppHost`. Aspire Dashboard запустится автоматически, предоставляя удобный мониторинг БД, бота и веб-интерфейса.
|
||||
|
||||
> [!NOTE]
|
||||
> При использовании **Dapper** в режиме Native AOT, все SQL-запросы используют строго типизированные DTO. Динамические типы (`dynamic`) не поддерживаются.
|
||||
├── src/
|
||||
│ ├── GmRelay.AppHost/ # .NET Aspire orchestrator
|
||||
│ ├── GmRelay.Bot/ # Telegram-бот (Native AOT)
|
||||
│ ├── GmRelay.Migrator/ # DbUp-миграции
|
||||
│ ├── GmRelay.ServiceDefaults/ # Aspire service defaults
|
||||
│ ├── GmRelay.Shared/ # Общие доменные модели
|
||||
│ ├── GmRelay.Web/ # Blazor Server dashboard
|
||||
│ └── GmRelay.Worker/ # Background workers
|
||||
├── tests/
|
||||
│ └── GmRelay.Bot.Tests/ # xUnit + NSubstitute
|
||||
├── compose.yaml # Docker Compose (AMD64 + ARM64)
|
||||
└── .env.example # Шаблон переменных окружения
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📜 Лицензия
|
||||
Проект распространяется под лицензией MIT. Использование в некоммерческих целях приветствуется.
|
||||
|
||||
MIT License. См. [LICENSE](./LICENSE).
|
||||
|
||||
---
|
||||
|
||||
*Построено с ❤️ для TTRPG-сообщества.*
|
||||
|
||||
+4
-2
@@ -17,7 +17,7 @@ services:
|
||||
retries: 10
|
||||
|
||||
bot:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:1.4.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:1.10.2
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
@@ -25,11 +25,12 @@ services:
|
||||
environment:
|
||||
- "ConnectionStrings__gmrelaydb=Host=db;Port=5432;Database=gmrelay_db;Username=gmrelay;Password=${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}"
|
||||
- "Telegram__BotToken=${TELEGRAM_BOT_TOKEN:?Set TELEGRAM_BOT_TOKEN in .env}"
|
||||
- "Telegram__MiniAppUrl=${TELEGRAM_MINI_APP_URL:-}"
|
||||
networks:
|
||||
- gmrelay
|
||||
|
||||
web:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:1.4.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:1.10.2
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
@@ -38,6 +39,7 @@ services:
|
||||
- "ConnectionStrings__gmrelaydb=Host=db;Port=5432;Database=gmrelay_db;Username=gmrelay;Password=${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}"
|
||||
- "Telegram__BotToken=${TELEGRAM_BOT_TOKEN:?Set TELEGRAM_BOT_TOKEN in .env}"
|
||||
- "Telegram__BotUsername=${TELEGRAM_BOT_USERNAME:?Set TELEGRAM_BOT_USERNAME in .env}"
|
||||
- "Telegram__MiniAppUrl=${TELEGRAM_MINI_APP_URL:-}"
|
||||
ports:
|
||||
- "${GMRELAY_WEB_PORT:-8080}:8080"
|
||||
volumes:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# ADR 002: Platform-Neutral Batch Rendering
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** — implemented in v1.10.0 (PR #42).
|
||||
|
||||
## Context
|
||||
|
||||
`SessionBatchRenderer` жил в `GmRelay.Shared` и напрямую зависел от `Telegram.Bot` (`InlineKeyboardMarkup`, `ParseMode.Html`). Это создавало проблемы:
|
||||
|
||||
1. **Shared не был platform-neutral.** Любой платформенный проект (Discord, Slack, WebSocket) тащил Telegram-зависимость.
|
||||
2. **Дублирование логики.** `GmRelay.Web` использовал тот же рендерер через прямую зависимость от `Shared`, но Web — это не Telegram-клиент.
|
||||
3. **Невозможно написать unit-тесты без Telegram-объектов.** Smoke-тесты создавали InlineKeyboardMarkup даже для проверки чисто доменной логики.
|
||||
|
||||
## Decision
|
||||
|
||||
Разделить рендеринг на две стадии:
|
||||
|
||||
1. **View Builder (platform-neutral)** — собирает view model из доменных DTO.
|
||||
2. **Platform Renderer (platform-specific)** — превращает view model в платформенное представление.
|
||||
|
||||
```
|
||||
Domain DTOs
|
||||
│
|
||||
▼
|
||||
SessionBatchViewBuilder (Shared)
|
||||
│
|
||||
▼
|
||||
SessionBatchViewModel (platform-neutral)
|
||||
│
|
||||
├──► TelegramSessionBatchRenderer ──► HTML + InlineKeyboardMarkup
|
||||
│
|
||||
└──► DiscordSessionBatchRenderer ──► (issue #26)
|
||||
```
|
||||
|
||||
### Изменённые компоненты
|
||||
|
||||
| Компонент | Было | Стало |
|
||||
|---|---|---|
|
||||
| `SessionBatchRenderer` | `GmRelay.Shared.Rendering` | Удалён |
|
||||
| `SessionBatchViewBuilder` | — | `GmRelay.Shared.Rendering` |
|
||||
| `SessionBatchViewModel` | — | `GmRelay.Shared.Rendering` |
|
||||
| `TelegramSessionBatchRenderer` | — | `GmRelay.Bot` + `GmRelay.Web` |
|
||||
| `DiscordSessionBatchRenderer` | — | `GmRelay.Shared.Rendering` (stub) |
|
||||
| `BatchMessageEditor` | `GmRelay.Shared.Rendering` | `GmRelay.Bot` + `GmRelay.Web` |
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
|
||||
- `GmRelay.Shared` больше не зависит от `Telegram.Bot`. Чистый platform-agnostic проект.
|
||||
- Можно добавить `DiscordSessionBatchRenderer` без изменений в `Shared`.
|
||||
- Unit-тесты ViewBuilder не создают `InlineKeyboardMarkup`.
|
||||
- Логика подсчёта игроков, сортировки сессий и генерации действий — в одном месте (ViewBuilder).
|
||||
|
||||
### Negative
|
||||
|
||||
- **Временное дублирование.** `TelegramSessionBatchRenderer` и `BatchMessageEditor` скопированы в `Bot` и `Web`. Планируется вынести в `GmRelay.Shared.Telegram` при появлении третьего Telegram-потребителя.
|
||||
- **Дополнительная стадия.** Теперь два вызова вместо одного: `Build` + `Render`. Этоtrade-off за чистоту абстракции.
|
||||
|
||||
## Related
|
||||
|
||||
- Issue #22 — этот рефакторинг.
|
||||
- Issue #26 — Discord Bot MVP (потребитель новой архитектуры).
|
||||
- ADR 001 — vertical slice, native AOT, Aspire (`docs/adr/0001-use-vertical-slice-native-aot-and-aspire.md`).
|
||||
@@ -0,0 +1,438 @@
|
||||
# Player List + Kick + Waitlist Promotion Implementation Plan
|
||||
|
||||
> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Add a player list (with names) to the Web UI session views, allow GM to kick a specific player, and auto-promote the next waitlisted player.
|
||||
|
||||
**Architecture:** Extend `ISessionStore` with participant queries and a remove method. Update `GroupDetails.razor` to show expandable participant lists. Reuse existing `PromoteWaitlistedPlayerAsync` logic after removal.
|
||||
|
||||
**Tech Stack:** C# 14, Blazor SSR, Dapper, PostgreSQL
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add domain model for WebParticipant
|
||||
|
||||
**Objective:** Create a DTO to represent a session participant in the web layer.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Services/SessionService.cs`
|
||||
|
||||
**Step 1: Add record**
|
||||
|
||||
```csharp
|
||||
public sealed record WebParticipant(
|
||||
Guid Id,
|
||||
long TelegramId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
string RsvpStatus,
|
||||
string RegistrationStatus,
|
||||
bool IsGm,
|
||||
DateTime? RespondedAt);
|
||||
```
|
||||
|
||||
**Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Web/Services/SessionService.cs
|
||||
git commit -m "feat: add WebParticipant record"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Add GetSessionParticipantsAsync to ISessionStore
|
||||
|
||||
**Objective:** Retrieve all participants for a session with full player info.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Services/ISessionStore.cs`
|
||||
- Modify: `src/GmRelay.Web/Services/SessionService.cs`
|
||||
- Modify: `src/GmRelay.Web/Services/AuthorizedSessionService.cs`
|
||||
|
||||
**Step 1: Add to interface**
|
||||
|
||||
In `ISessionStore.cs`, add:
|
||||
```csharp
|
||||
Task<List<WebParticipant>> GetSessionParticipantsAsync(Guid sessionId);
|
||||
```
|
||||
|
||||
**Step 2: Implement in SessionService**
|
||||
|
||||
In `SessionService.cs`, add:
|
||||
```csharp
|
||||
public async Task<List<WebParticipant>> GetSessionParticipantsAsync(Guid sessionId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return (await conn.QueryAsync<WebParticipant>(
|
||||
"""
|
||||
SELECT sp.id AS Id,
|
||||
p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
sp.rsvp_status AS RsvpStatus,
|
||||
sp.registration_status AS RegistrationStatus,
|
||||
sp.is_gm AS IsGm,
|
||||
sp.responded_at AS RespondedAt
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
ORDER BY sp.is_gm DESC,
|
||||
CASE sp.registration_status WHEN 'Active' THEN 0 ELSE 1 END,
|
||||
sp.created_at
|
||||
""",
|
||||
new { SessionId = sessionId })).ToList();
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3: Add authorized wrapper**
|
||||
|
||||
In `AuthorizedSessionService.cs`, add:
|
||||
```csharp
|
||||
public async Task<List<WebParticipant>?> GetSessionParticipantsForGmAsync(Guid sessionId, long gmId)
|
||||
{
|
||||
var session = await GetSessionForGmAsync(sessionId, gmId);
|
||||
if (session is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return await sessionStore.GetSessionParticipantsAsync(sessionId);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Web/Services/ISessionStore.cs
|
||||
|
||||
git add src/GmRelay.Web/Services/SessionService.cs
|
||||
|
||||
git add src/GmRelay.Web/Services/AuthorizedSessionService.cs
|
||||
|
||||
git commit -m "feat: add GetSessionParticipantsAsync"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Add RemovePlayerFromSessionAsync with waitlist promotion
|
||||
|
||||
**Objective:** Allow GM to remove a specific player; auto-promote next waitlisted player if conditions met.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Services/ISessionStore.cs`
|
||||
- Modify: `src/GmRelay.Web/Services/SessionService.cs`
|
||||
- Modify: `src/GmRelay.Web/Services/AuthorizedSessionService.cs`
|
||||
|
||||
**Step 1: Add to interface**
|
||||
|
||||
In `ISessionStore.cs`, add:
|
||||
```csharp
|
||||
Task RemovePlayerFromSessionAsync(Guid sessionId, Guid groupId, Guid participantId);
|
||||
```
|
||||
|
||||
**Step 2: Implement in SessionService**
|
||||
|
||||
In `SessionService.cs`, add:
|
||||
```csharp
|
||||
public async Task RemovePlayerFromSessionAsync(Guid sessionId, Guid groupId, Guid participantId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
await using var transaction = await conn.BeginTransactionAsync();
|
||||
|
||||
var session = await conn.QuerySingleOrDefaultAsync<WebSession>(
|
||||
@"SELECT s.id, s.group_id AS GroupId, s.title, s.scheduled_at AS ScheduledAt, s.status, s.join_link AS JoinLink,
|
||||
s.batch_id AS BatchId, s.batch_message_id AS BatchMessageId,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.max_players AS MaxPlayers,
|
||||
0 AS ActivePlayerCount,
|
||||
0 AS WaitlistedPlayerCount,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.id = @SessionId AND s.group_id = @GroupId
|
||||
FOR UPDATE",
|
||||
new { SessionId = sessionId, GroupId = groupId },
|
||||
transaction);
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
throw new SessionAccessDeniedException(sessionId, 0);
|
||||
}
|
||||
|
||||
// Verify participant exists in this session
|
||||
var participant = await conn.QuerySingleOrDefaultAsync<WebParticipant>(
|
||||
"""
|
||||
SELECT sp.id AS Id,
|
||||
p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
sp.rsvp_status AS RsvpStatus,
|
||||
sp.registration_status AS RegistrationStatus,
|
||||
sp.is_gm AS IsGm,
|
||||
sp.responded_at AS RespondedAt
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.id = @ParticipantId AND sp.session_id = @SessionId
|
||||
""",
|
||||
new { ParticipantId = participantId, SessionId = sessionId },
|
||||
transaction);
|
||||
|
||||
if (participant is null)
|
||||
{
|
||||
throw new InvalidOperationException("Участник не найден в этой сессии.");
|
||||
}
|
||||
|
||||
bool wasActive = participant.RegistrationStatus == ParticipantRegistrationStatus.Active;
|
||||
|
||||
await conn.ExecuteAsync(
|
||||
"DELETE FROM session_participants WHERE id = @ParticipantId",
|
||||
new { ParticipantId = participantId },
|
||||
transaction);
|
||||
|
||||
WebPromotedParticipantDto? promoted = null;
|
||||
|
||||
if (wasActive)
|
||||
{
|
||||
promoted = await conn.QuerySingleOrDefaultAsync<WebPromotedParticipantDto>(
|
||||
"""
|
||||
SELECT sp.id AS ParticipantRowId,
|
||||
p.display_name AS DisplayName
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Waitlisted
|
||||
ORDER BY sp.created_at ASC, sp.id ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE OF sp
|
||||
""",
|
||||
new { SessionId = sessionId, Waitlisted = ParticipantRegistrationStatus.Waitlisted },
|
||||
transaction);
|
||||
|
||||
if (promoted is not null)
|
||||
{
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
UPDATE session_participants
|
||||
SET registration_status = @Active,
|
||||
rsvp_status = @Pending,
|
||||
responded_at = NULL
|
||||
WHERE id = @ParticipantRowId
|
||||
""",
|
||||
new
|
||||
{
|
||||
promoted.ParticipantRowId,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Pending = RsvpStatus.Pending
|
||||
},
|
||||
transaction);
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.CommitAsync();
|
||||
|
||||
// Notifications
|
||||
await bot.SendMessage(
|
||||
session.TelegramChatId,
|
||||
$"🚪 <b>{System.Net.WebUtility.HtmlEncode(participant.DisplayName)}</b> удален(а) из сессии «{System.Net.WebUtility.HtmlEncode(session.Title)}».",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
|
||||
if (promoted is not null)
|
||||
{
|
||||
await bot.SendMessage(
|
||||
session.TelegramChatId,
|
||||
$"⬆️ <b>{System.Net.WebUtility.HtmlEncode(promoted.DisplayName)}</b> переведен(а) из листа ожидания в основной состав «{System.Net.WebUtility.HtmlEncode(session.Title)}».",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
}
|
||||
|
||||
if (session.BatchMessageId.HasValue)
|
||||
{
|
||||
await TryUpdateBatchMessageAsync(session.BatchId, session.TelegramChatId, session.BatchMessageId.Value, session.Title);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3: Add authorized wrapper**
|
||||
|
||||
In `AuthorizedSessionService.cs`, add:
|
||||
```csharp
|
||||
public async Task RemovePlayerFromSessionForGmAsync(Guid sessionId, long gmId, Guid participantId)
|
||||
{
|
||||
var session = await GetSessionForGmAsync(sessionId, gmId);
|
||||
if (session is null)
|
||||
{
|
||||
throw new SessionAccessDeniedException(sessionId, gmId);
|
||||
}
|
||||
|
||||
await sessionStore.RemovePlayerFromSessionAsync(sessionId, session.GroupId, participantId);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Web/Services/ISessionStore.cs
|
||||
|
||||
git add src/GmRelay.Web/Services/SessionService.cs
|
||||
|
||||
git add src/GmRelay.Web/Services/AuthorizedSessionService.cs
|
||||
|
||||
git commit -m "feat: add RemovePlayerFromSessionAsync with waitlist promotion"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Modify GroupDetails.razor to show participant list
|
||||
|
||||
**Objective:** Add expandable player lists to each session row with kick buttons.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Components/Pages/GroupDetails.razor`
|
||||
|
||||
**Step 1:** Add `participants` dictionary and `kickingParticipantId` state variables.
|
||||
|
||||
**Step 2:** Add `LoadParticipants(Guid sessionId)` and `KickParticipant(Guid sessionId, Guid participantId)` methods.
|
||||
|
||||
**Step 3:** In desktop table, add a new column or expand row with participant list.
|
||||
|
||||
**Step 4:** In mobile cards, add expandable participant section.
|
||||
|
||||
**Step 5:** Add styles to `app.css` if needed (badge styles are already present).
|
||||
|
||||
**Step 6:** Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Web/Components/Pages/GroupDetails.razor
|
||||
|
||||
git add src/GmRelay.Web/wwwroot/app.css
|
||||
|
||||
git commit -m "feat: show player list and kick button in GroupDetails"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Modify EditSession.razor to show participant list
|
||||
|
||||
**Objective:** Show participant list on the edit page with kick capability.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Components/Pages/EditSession.razor`
|
||||
|
||||
**Step 1:** Load participants in `OnInitializedAsync`.
|
||||
|
||||
**Step 2:** Render participant list below the edit form.
|
||||
|
||||
**Step 3:** Add kick button for each non-GM participant.
|
||||
|
||||
**Step 4:** Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Web/Components/Pages/EditSession.razor
|
||||
|
||||
git commit -m "feat: show player list and kick button in EditSession"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Add backend tests
|
||||
|
||||
**Objective:** Cover new GetSessionParticipants and RemovePlayerFromSession logic.
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Web/SessionParticipantTests.cs`
|
||||
|
||||
**Step 1:** Write tests for `GetSessionParticipantsForGmAsync`.
|
||||
|
||||
**Step 2:** Write tests for `RemovePlayerFromSessionForGmAsync` including waitlist promotion.
|
||||
|
||||
**Step 3:** Run tests
|
||||
|
||||
```bash
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj -v n
|
||||
```
|
||||
|
||||
**Step 4:** Commit
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Web/SessionParticipantTests.cs
|
||||
|
||||
git commit -m "test: add SessionParticipant service tests"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Update README
|
||||
|
||||
**Objective:** Bump version and document new features.
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
|
||||
**Step 1:** Change version from `v1.9.6` to `v1.9.7`.
|
||||
|
||||
**Step 2:** Add bullet under Web Dashboard: player list with kick and auto-promote.
|
||||
|
||||
**Step 3:** Commit
|
||||
|
||||
```bash
|
||||
git add README.md
|
||||
|
||||
git commit -m "docs: bump README to v1.9.7, document player list kick"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Update Wiki
|
||||
|
||||
**Objective:** Update `Руководство ГМа` page with player management instructions.
|
||||
|
||||
**Files:**
|
||||
- Modify: Wiki page `Руководство ГМа`
|
||||
|
||||
**Step 1:** Read current wiki content via MCP.
|
||||
|
||||
**Step 2:** Add section about viewing player list and removing players.
|
||||
|
||||
**Step 3:** Update via MCP.
|
||||
|
||||
---
|
||||
|
||||
## Task 9: Push branch and run CI
|
||||
|
||||
**Objective:** Push branch, monitor workflow, fix issues.
|
||||
|
||||
**Step 1:** Push
|
||||
|
||||
```bash
|
||||
git push -u origin feat/player-list-kick-waitlist
|
||||
```
|
||||
|
||||
**Step 2:** Check workflow run via MCP gitea actions.
|
||||
|
||||
**Step 3:** Fix any issues.
|
||||
|
||||
---
|
||||
|
||||
## Task 10: Merge and create release
|
||||
|
||||
**Objective:** Merge PR (or fast-forward), tag, create release.
|
||||
|
||||
**Step 1:** Merge to main
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
|
||||
git merge --no-ff feat/player-list-kick-waitlist -m "feat: player list, kick, and waitlist promotion (#X)"
|
||||
```
|
||||
|
||||
**Step 2:** Tag v1.9.7
|
||||
|
||||
```bash
|
||||
git tag v1.9.7
|
||||
|
||||
git push origin main --tags
|
||||
```
|
||||
|
||||
**Step 3:** Create release via MCP gitea_create_release.
|
||||
|
||||
---
|
||||
@@ -0,0 +1,69 @@
|
||||
# Telegram Mini App Dashboard Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a Telegram Mini App mobile dashboard that reuses the existing Web Dashboard and validates Telegram WebApp `initData` on the server.
|
||||
|
||||
**Architecture:** Extend `TelegramAuthService` for WebApp init data, add a `/miniapp` Blazor entry page plus `/auth/telegram-webapp` endpoint, and add bot entry points through an inline WebApp button and optional menu button setup. Existing application/domain services remain the only write path.
|
||||
|
||||
**Tech Stack:** .NET 10, Blazor Server, Telegram.Bot, xUnit, Dapper/Npgsql-backed existing services.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Telegram WebApp Authentication
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Services/TelegramAuthService.cs`
|
||||
- Modify: `src/GmRelay.Web/Program.cs`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Web/TelegramAuthServiceTests.cs`
|
||||
|
||||
- [ ] Write failing tests for valid WebApp `initData`, tampered hash, and expired auth date.
|
||||
- [ ] Run `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter TelegramAuthServiceTests`.
|
||||
- [ ] Implement WebApp HMAC verification using the Telegram `WebAppData` secret derivation.
|
||||
- [ ] Add `/auth/telegram-webapp` endpoint that signs in using the same claims as `/auth/telegram`.
|
||||
- [ ] Re-run the filtered tests.
|
||||
|
||||
### Task 2: Mini App Entry Page
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Web/Components/Pages/MiniApp.razor`
|
||||
- Modify: `src/GmRelay.Web/Components/App.razor`
|
||||
- Modify: `src/GmRelay.Web/wwwroot/app.css`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Web/MiniAppDashboardTests.cs`
|
||||
|
||||
- [ ] Write failing tests that assert `/miniapp`, `telegram-web-app.js`, `authenticateTelegramMiniApp`, and Mini App CSS hooks exist.
|
||||
- [ ] Run `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter MiniAppDashboardTests`.
|
||||
- [ ] Implement `/miniapp` to post `Telegram.WebApp.initData` to `/auth/telegram-webapp`, expand/ready the Mini App, and show fallback login when opened outside Telegram.
|
||||
- [ ] Add CSS for a mobile-first Mini App shell and compact dashboard spacing.
|
||||
- [ ] Re-run the filtered tests.
|
||||
|
||||
### Task 3: Bot Entry Points
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Bot/Infrastructure/Telegram/TelegramMiniAppMenuButtonService.cs`
|
||||
- Modify: `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs`
|
||||
- Modify: `src/GmRelay.Bot/Program.cs`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Infrastructure/Telegram/TelegramMiniAppEntryPointTests.cs`
|
||||
|
||||
- [ ] Write failing tests that assert `/start` exposes a WebApp button and startup registers the menu button service.
|
||||
- [ ] Run `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter TelegramMiniAppEntryPointTests`.
|
||||
- [ ] Add a configurable `Telegram:MiniAppUrl` entry point; when missing, keep existing command behavior.
|
||||
- [ ] Add hosted service that calls `SetChatMenuButton` with `MenuButtonWebApp` only when the URL is configured.
|
||||
- [ ] Re-run the filtered tests.
|
||||
|
||||
### Task 4: Docs, Versions, and Release Prep
|
||||
|
||||
**Files:**
|
||||
- Modify: `Directory.Build.props`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `.gitea/workflows/deploy.yml`
|
||||
- Modify: `src/GmRelay.Web/wwwroot/app.css`
|
||||
- Modify: `src/GmRelay.Web/Components/Layout/NavMenu.razor`
|
||||
- Modify: `README.md`
|
||||
- Wiki: `Home`, `Быстрый старт`, `Руководство ГМа`, `Развёртывание`, `Архитектура`, `Разработка`
|
||||
|
||||
- [ ] Update project/container/workflow/UI versions to `1.9.0`.
|
||||
- [ ] Document `TELEGRAM_MINI_APP_URL`, BotFather `/setmenubutton`, `/miniapp`, and WebApp auth.
|
||||
- [ ] Run `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --collect:"XPlat Code Coverage"`.
|
||||
- [ ] Run `dotnet build GM-Relay.slnx -c Release`.
|
||||
- [ ] Commit, push, close issue #17, update wiki, create tag/release `v1.9.0`.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Telegram Mini App Dashboard Design
|
||||
|
||||
## Goal
|
||||
|
||||
Issue #17 adds a Telegram Mini App dashboard as the mobile entry point for the existing Web Dashboard. Owner and co-GM users must be able to open the dashboard from Telegram, pass server-side Telegram WebApp `initData` validation, and manage only their own groups.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add Mini App authentication using Telegram WebApp `initData`.
|
||||
- Add a `/miniapp` entry page that signs the user into the existing cookie auth flow, then opens the regular dashboard UI in mobile-first mode.
|
||||
- Reuse `AuthorizedSessionService`, `SessionService`, and existing Blazor pages for groups, sessions, templates, waitlist promotion, edit forms, and bulk batch operations.
|
||||
- Add bot entry points: a Mini App button in `/start` and a configurable default menu button when `Telegram:MiniAppUrl` is set.
|
||||
- Update README, wiki, deployment config, and visible version strings to `1.9.0`.
|
||||
|
||||
## Architecture
|
||||
|
||||
The Mini App is not a second dashboard implementation. It is a Telegram-authenticated entrance into the existing Blazor dashboard. This keeps authorization, domain operations, Telegram message synchronization, and Web Dashboard behavior in one place.
|
||||
|
||||
`TelegramAuthService` gains a second verification method for WebApp `initData`. The server accepts the raw URL-encoded init payload at `/auth/telegram-webapp`, verifies the Telegram HMAC with the bot token, extracts the user id/name from the embedded `user` JSON, and issues the same auth cookie as the login widget endpoint.
|
||||
|
||||
`/miniapp` loads `telegram-web-app.js`, posts `window.Telegram.WebApp.initData` to the server endpoint, expands the WebApp viewport, and redirects to `/`. If a user opens `/miniapp` outside Telegram, the page shows the regular login fallback.
|
||||
|
||||
## Data Flow
|
||||
|
||||
1. User opens the Mini App from the bot menu button or `/start` inline button.
|
||||
2. Telegram injects `initData` into the WebApp JavaScript API.
|
||||
3. `/miniapp` posts `{ initData }` to `/auth/telegram-webapp`.
|
||||
4. The server verifies the WebApp signature and expiry.
|
||||
5. The server creates the same claims used by Telegram Login Widget.
|
||||
6. Existing Blazor pages load groups through `AuthorizedSessionService`.
|
||||
7. Any edit, waitlist, template, or batch action still goes through existing services and keeps Telegram messages synchronized.
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Missing or invalid init data returns `401` and leaves the user on the Mini App page.
|
||||
- Expired auth data is rejected with the same 24-hour window used by the Login Widget.
|
||||
- A verified Telegram user with no owner/co-GM groups sees the existing empty dashboard state.
|
||||
- Direct navigation to a foreign group/session still redirects to `/access-denied` through existing authorization checks.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests cover valid and invalid WebApp `initData`.
|
||||
- File-level regression tests ensure `/miniapp`, `/auth/telegram-webapp`, Telegram WebApp script loading, bot Mini App button, menu button setup, and mobile Mini App CSS hooks remain present.
|
||||
- Existing `AuthorizedSessionServiceTests` continue covering owner/co-GM access behavior.
|
||||
@@ -1,4 +1,5 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
@@ -13,7 +14,8 @@ internal sealed record SessionInfo(
|
||||
string Title,
|
||||
DateTime ScheduledAt,
|
||||
Guid GroupId,
|
||||
long TelegramChatId);
|
||||
long TelegramChatId,
|
||||
string NotificationMode);
|
||||
|
||||
internal sealed record ParticipantInfo(
|
||||
long TelegramId,
|
||||
@@ -29,6 +31,7 @@ internal sealed record ParticipantInfo(
|
||||
public sealed class SendConfirmationHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<SendConfirmationHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(Guid sessionId, CancellationToken ct)
|
||||
@@ -39,7 +42,8 @@ public sealed class SendConfirmationHandler(
|
||||
var session = await connection.QuerySingleOrDefaultAsync<SessionInfo>(
|
||||
"""
|
||||
SELECT s.id, s.title, s.scheduled_at AS ScheduledAt, s.group_id AS GroupId,
|
||||
g.telegram_chat_id AS TelegramChatId
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.id = @SessionId AND s.status = @Planned
|
||||
@@ -115,6 +119,26 @@ public sealed class SendConfirmationHandler(
|
||||
MessageId = message.MessageId
|
||||
});
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(session.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
var directText = $"""
|
||||
🎲 <b>Подтвердите участие в игре</b>
|
||||
|
||||
📌 <b>{System.Net.WebUtility.HtmlEncode(session.Title)}</b>
|
||||
📅 {session.ScheduledAt.FormatMoscow()} (МСК)
|
||||
|
||||
Ответьте кнопкой в групповом сообщении расписания.
|
||||
""";
|
||||
|
||||
await directSender.SendAsync(
|
||||
participants.Select(p => new DirectNotificationRecipient(p.TelegramId, p.DisplayName)),
|
||||
directText,
|
||||
"confirmation",
|
||||
sessionId,
|
||||
ct);
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Confirmation sent for session {SessionId} ({Title}), message_id={MessageId}",
|
||||
sessionId, session.Title, message.MessageId);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
|
||||
namespace GmRelay.Bot.Features.Notifications;
|
||||
|
||||
public sealed record DirectNotificationRecipient(long TelegramId, string DisplayName);
|
||||
|
||||
public sealed class DirectSessionNotificationSender(
|
||||
ITelegramBotClient bot,
|
||||
ILogger<DirectSessionNotificationSender> logger)
|
||||
{
|
||||
public async Task SendAsync(
|
||||
IEnumerable<DirectNotificationRecipient> recipients,
|
||||
string htmlText,
|
||||
string notificationKind,
|
||||
Guid sessionId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
foreach (var recipient in recipients)
|
||||
{
|
||||
try
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: recipient.TelegramId,
|
||||
text: htmlText,
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(
|
||||
ex,
|
||||
"Failed to send {NotificationKind} DM for session {SessionId} to player {TelegramId} ({DisplayName})",
|
||||
notificationKind,
|
||||
sessionId,
|
||||
recipient.TelegramId,
|
||||
recipient.DisplayName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
@@ -12,7 +13,8 @@ internal sealed record JoinLinkSession(
|
||||
string Title,
|
||||
string JoinLink,
|
||||
DateTime ScheduledAt,
|
||||
long TelegramChatId);
|
||||
long TelegramChatId,
|
||||
string NotificationMode);
|
||||
|
||||
internal sealed record ConfirmedPlayer(
|
||||
long TelegramId,
|
||||
@@ -28,6 +30,7 @@ internal sealed record ConfirmedPlayer(
|
||||
public sealed class SendJoinLinkHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<SendJoinLinkHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(Guid sessionId, CancellationToken ct)
|
||||
@@ -38,7 +41,8 @@ public sealed class SendJoinLinkHandler(
|
||||
var session = await connection.QuerySingleOrDefaultAsync<JoinLinkSession>(
|
||||
"""
|
||||
SELECT s.id, s.title, s.join_link AS JoinLink, s.scheduled_at AS ScheduledAt,
|
||||
g.telegram_chat_id AS TelegramChatId
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.id = @SessionId
|
||||
@@ -102,6 +106,24 @@ public sealed class SendJoinLinkHandler(
|
||||
""",
|
||||
new { SessionId = sessionId, MessageId = message.MessageId });
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(session.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
var directText = $"""
|
||||
🎮 <b>Игра начинается через 5 минут</b>
|
||||
|
||||
📌 <b>{System.Net.WebUtility.HtmlEncode(session.Title)}</b>
|
||||
🔗 {System.Net.WebUtility.HtmlEncode(session.JoinLink)}
|
||||
""";
|
||||
|
||||
await directSender.SendAsync(
|
||||
players.Select(p => new DirectNotificationRecipient(p.TelegramId, p.DisplayName)),
|
||||
directText,
|
||||
"join-link",
|
||||
sessionId,
|
||||
ct);
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Join link sent for session {SessionId} ({Title}), message_id={MessageId}",
|
||||
sessionId, session.Title, message.MessageId);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.Bot.Features.Reminders.SendOneHourReminder;
|
||||
|
||||
internal sealed record OneHourReminderSession(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string JoinLink,
|
||||
DateTime ScheduledAt,
|
||||
string NotificationMode);
|
||||
|
||||
public sealed class SendOneHourReminderHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<SendOneHourReminderHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(Guid sessionId, CancellationToken ct)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
|
||||
var session = await connection.QuerySingleOrDefaultAsync<OneHourReminderSession>(
|
||||
"""
|
||||
SELECT id,
|
||||
title,
|
||||
join_link AS JoinLink,
|
||||
scheduled_at AS ScheduledAt,
|
||||
notification_mode AS NotificationMode
|
||||
FROM sessions
|
||||
WHERE id = @SessionId
|
||||
AND status IN (@Confirmed, @ConfirmationSent)
|
||||
AND one_hour_reminder_processed_at IS NULL
|
||||
""",
|
||||
new
|
||||
{
|
||||
SessionId = sessionId,
|
||||
Confirmed = SessionStatus.Confirmed,
|
||||
ConfirmationSent = SessionStatus.ConfirmationSent
|
||||
});
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
logger.LogWarning("Session {SessionId} not eligible for one-hour reminder", sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
var recipients = (await connection.QueryAsync<DirectNotificationRecipient>(
|
||||
"""
|
||||
SELECT p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
AND sp.rsvp_status != @Declined
|
||||
""",
|
||||
new
|
||||
{
|
||||
SessionId = sessionId,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Declined = RsvpStatus.Declined
|
||||
})).ToList();
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(session.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages() && recipients.Count > 0)
|
||||
{
|
||||
var text = $"""
|
||||
⏰ <b>Игра начнётся примерно через 1 час</b>
|
||||
|
||||
📌 <b>{System.Net.WebUtility.HtmlEncode(session.Title)}</b>
|
||||
📅 {session.ScheduledAt.FormatMoscow()} (МСК)
|
||||
🔗 {System.Net.WebUtility.HtmlEncode(session.JoinLink)}
|
||||
""";
|
||||
|
||||
await directSender.SendAsync(recipients, text, "one-hour-reminder", session.Id, ct);
|
||||
}
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET one_hour_reminder_processed_at = now(),
|
||||
updated_at = now()
|
||||
WHERE id = @SessionId
|
||||
AND one_hour_reminder_processed_at IS NULL
|
||||
""",
|
||||
new { SessionId = sessionId });
|
||||
|
||||
logger.LogInformation(
|
||||
"One-hour reminder processed for session {SessionId} ({Title}) with mode {NotificationMode}",
|
||||
sessionId,
|
||||
session.Title,
|
||||
session.NotificationMode);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
@@ -15,11 +17,12 @@ public sealed record CancelSessionCommand(
|
||||
int MessageId);
|
||||
|
||||
// DTOs for AOT compilation
|
||||
internal sealed record CancelSessionInfoDto(string Title, Guid BatchId, long GmId);
|
||||
internal sealed record CancelSessionInfoDto(string Title, Guid BatchId, int? BatchMessageId, bool CanManage, string NotificationMode);
|
||||
|
||||
public sealed class CancelSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<CancelSessionHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(CancelSessionCommand command, CancellationToken ct)
|
||||
@@ -27,13 +30,24 @@ public sealed class CancelSessionHandler(
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
await using var transaction = await connection.BeginTransactionAsync(ct);
|
||||
|
||||
// 1. Проверяем, что запрос делает ГМ данной сессии
|
||||
// 1. Проверяем, что запрос делает управляющий данной группы.
|
||||
var session = await connection.QuerySingleOrDefaultAsync<CancelSessionInfoDto>(
|
||||
@"SELECT s.title as Title, s.batch_id as BatchId, g.gm_telegram_id as GmId
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
WHERE s.id = @SessionId",
|
||||
new { command.SessionId }, transaction);
|
||||
"""
|
||||
SELECT s.title AS Title,
|
||||
s.batch_id AS BatchId,
|
||||
s.batch_message_id AS BatchMessageId,
|
||||
s.notification_mode AS NotificationMode,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND p.telegram_id = @TelegramUserId
|
||||
) AS CanManage
|
||||
FROM sessions s
|
||||
WHERE s.id = @SessionId
|
||||
""",
|
||||
new { command.SessionId, command.TelegramUserId }, transaction);
|
||||
|
||||
if (session == null)
|
||||
{
|
||||
@@ -41,9 +55,9 @@ public sealed class CancelSessionHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.GmId != command.TelegramUserId)
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только Мастер Игры (GM) может отменять сессию.", showAlert: true, cancellationToken: ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только owner или co-GM может отменять сессию.", showAlert: true, cancellationToken: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -73,25 +87,50 @@ public sealed class CancelSessionHandler(
|
||||
ORDER BY sp.registration_status ASC, sp.created_at ASC, sp.responded_at ASC, p.created_at ASC",
|
||||
new { BatchId = session.BatchId }, transaction);
|
||||
|
||||
var directRecipients = (await connection.QueryAsync<DirectNotificationRecipient>(
|
||||
"""
|
||||
SELECT p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName
|
||||
FROM session_participants sp
|
||||
JOIN players p ON sp.player_id = p.id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
""",
|
||||
new { command.SessionId, Active = ParticipantRegistrationStatus.Active },
|
||||
transaction)).ToList();
|
||||
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
// 4. Перерисовываем сообщение
|
||||
var renderResult = SessionBatchRenderer.Render(session.Title, batchSessions.ToList(), batchParticipants.ToList());
|
||||
var view = SessionBatchViewBuilder.Build(session.Title, batchSessions.ToList(), batchParticipants.ToList());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
messageId: session.BatchMessageId ?? command.MessageId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
replyMarkup: renderResult.Markup,
|
||||
ct);
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия отменена!", cancellationToken: ct);
|
||||
|
||||
// Опционально: написать отдельное сообщение в чат
|
||||
await bot.SendMessage(command.ChatId, $"❌ <b>Внимание!</b> Сессия \"{System.Net.WebUtility.HtmlEncode(session.Title)}\" отменена.", parseMode: Telegram.Bot.Types.Enums.ParseMode.Html, cancellationToken: ct);
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(session.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
await directSender.SendAsync(
|
||||
directRecipients,
|
||||
$"❌ <b>Сессия отменена</b>\n\n📌 <b>{System.Net.WebUtility.HtmlEncode(session.Title)}</b>",
|
||||
"session-cancelled",
|
||||
command.SessionId,
|
||||
ct);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -4,9 +4,12 @@ using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
internal sealed record SessionCreationGroupAccessDto(Guid GroupId, bool CanManage);
|
||||
|
||||
public sealed class CreateSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient botClient,
|
||||
@@ -14,7 +17,7 @@ public sealed class CreateSessionHandler(
|
||||
{
|
||||
public async Task HandleAsync(Message message, CancellationToken cancellationToken)
|
||||
{
|
||||
var parseResult = NewSessionCommandParser.Parse(message.Text, DateTimeOffset.UtcNow);
|
||||
var parseResult = NewSessionCommandParser.Parse(message.Text ?? message.Caption, DateTimeOffset.UtcNow);
|
||||
|
||||
foreach (var timeInput in parseResult.PastTimeInputs)
|
||||
{
|
||||
@@ -40,17 +43,26 @@ public sealed class CreateSessionHandler(
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
foreach (var recurringInput in parseResult.InvalidRecurringInputs)
|
||||
{
|
||||
await botClient.SendMessage(
|
||||
message.Chat.Id,
|
||||
$"⚠️ Предупреждение: некорректный повтор расписания '{recurringInput}'. Укажите число игр 1-52 и шаг 1-365 дней.",
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
if (!parseResult.IsValid)
|
||||
{
|
||||
await botClient.SendMessage(
|
||||
chatId: message.Chat.Id,
|
||||
text: "❌ Не удалось распознать формат. Пожалуйста, используйте шаблон:\n\n/newsession\nНазвание: My Game\nВремя: 15.05.2026 19:30\nВремя: 22.05.2026 19:30\nМест: 4\nСсылка: https://link",
|
||||
text: "❌ Не удалось распознать формат. Пожалуйста, используйте шаблон:\n\n/newsession\nНазвание: My Game\nВремя: 15.05.2026 19:30\nВремя: 22.05.2026 19:30\nМест: 4\nСсылка: https://link\nКартинка: https://cover\n\nДля повтора можно указать одну дату и строки:\nИгр: 4\nИнтервал: 7",
|
||||
cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
var title = parseResult.Title!;
|
||||
var link = parseResult.Link!;
|
||||
var imageReference = GetBatchImageReference(message, parseResult.ImageUrl);
|
||||
var gmId = message.From!.Id;
|
||||
var gmName = message.From.FirstName + (string.IsNullOrEmpty(message.From.LastName) ? string.Empty : $" {message.From.LastName}");
|
||||
var gmUsername = message.From.Username;
|
||||
@@ -74,16 +86,64 @@ public sealed class CreateSessionHandler(
|
||||
new { TgId = gmId, Name = gmName, Username = gmUsername },
|
||||
transaction);
|
||||
|
||||
var groupId = await connection.ExecuteScalarAsync<Guid>(
|
||||
var existingGroup = await connection.QuerySingleOrDefaultAsync<SessionCreationGroupAccessDto>(
|
||||
"""
|
||||
INSERT INTO game_groups (telegram_chat_id, name, gm_telegram_id)
|
||||
VALUES (@ChatId, @ChatName, @GmId)
|
||||
ON CONFLICT (telegram_chat_id) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id;
|
||||
SELECT g.id AS GroupId,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = g.id
|
||||
AND p.telegram_id = @GmId
|
||||
) AS CanManage
|
||||
FROM game_groups g
|
||||
WHERE g.telegram_chat_id = @ChatId
|
||||
""",
|
||||
new { ChatId = chatId, ChatName = chatTitle, GmId = gmId },
|
||||
new { ChatId = chatId, GmId = gmId },
|
||||
transaction);
|
||||
|
||||
Guid groupId;
|
||||
if (existingGroup is null)
|
||||
{
|
||||
groupId = await connection.ExecuteScalarAsync<Guid>(
|
||||
"""
|
||||
INSERT INTO game_groups (telegram_chat_id, name, gm_telegram_id)
|
||||
VALUES (@ChatId, @ChatName, @GmId)
|
||||
RETURNING id;
|
||||
""",
|
||||
new { ChatId = chatId, ChatName = chatTitle, GmId = gmId },
|
||||
transaction);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO group_managers (group_id, player_id, role)
|
||||
SELECT @GroupId, p.id, @OwnerRole
|
||||
FROM players p
|
||||
WHERE p.telegram_id = @GmId
|
||||
ON CONFLICT (group_id, player_id) DO NOTHING
|
||||
""",
|
||||
new { GroupId = groupId, GmId = gmId, OwnerRole = GroupManagerRoleExtensions.OwnerValue },
|
||||
transaction);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!existingGroup.CanManage)
|
||||
{
|
||||
await transaction.RollbackAsync(cancellationToken);
|
||||
await botClient.SendMessage(
|
||||
chatId,
|
||||
"⛔ Только owner или co-GM этой группы может создавать игровые сессии.",
|
||||
cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
groupId = existingGroup.GroupId;
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE game_groups SET name = @ChatName WHERE id = @GroupId",
|
||||
new { ChatName = chatTitle, GroupId = groupId },
|
||||
transaction);
|
||||
}
|
||||
|
||||
int? messageThreadId = null;
|
||||
if (message.Chat.IsForum)
|
||||
{
|
||||
@@ -124,15 +184,66 @@ public sealed class CreateSessionHandler(
|
||||
await transaction.CommitAsync(cancellationToken);
|
||||
logger.LogInformation("Создан батч {BatchId} с {Count} сессиями в группе {GroupId}", batchId, sessions.Count, groupId);
|
||||
|
||||
var renderResult = SessionBatchRenderer.Render(title, sessions, Array.Empty<ParticipantBatchDto>());
|
||||
var view = SessionBatchViewBuilder.Build(title, sessions, Array.Empty<ParticipantBatchDto>());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
var batchMessage = await botClient.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: messageThreadId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: cancellationToken);
|
||||
Message batchMessage;
|
||||
|
||||
if (imageReference is not null && renderResult.Text.Length <= 1024)
|
||||
{
|
||||
// Картинка + расписание умещаются в одном Telegram-фото с подписью
|
||||
try
|
||||
{
|
||||
batchMessage = await botClient.SendPhoto(
|
||||
chatId: chatId,
|
||||
messageThreadId: messageThreadId,
|
||||
photo: InputFile.FromString(imageReference),
|
||||
caption: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Не удалось отправить картинку для батча {BatchId}, отправляем текстом", batchId);
|
||||
batchMessage = await botClient.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: messageThreadId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Текст слишком длинный для caption — fallback на два сообщения
|
||||
if (imageReference is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await botClient.SendPhoto(
|
||||
chatId: chatId,
|
||||
messageThreadId: messageThreadId,
|
||||
photo: InputFile.FromString(imageReference),
|
||||
caption: $"🎲 {System.Net.WebUtility.HtmlEncode(title)}",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Не удалось отправить картинку для батча {BatchId}", batchId);
|
||||
}
|
||||
}
|
||||
|
||||
batchMessage = await botClient.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: messageThreadId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE sessions SET batch_message_id = @MsgId WHERE batch_id = @BatchId",
|
||||
@@ -157,4 +268,20 @@ public sealed class CreateSessionHandler(
|
||||
await botClient.SendMessage(chatId, "💥 Произошла ошибка базы данных при создании сессии.", cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
internal static string? GetBatchImageReference(Message message, string? parsedImageUrl)
|
||||
{
|
||||
var attachedPhotoFileId = message.Photo?
|
||||
.OrderByDescending(photo => photo.FileSize ?? 0)
|
||||
.ThenByDescending(photo => photo.Width * photo.Height)
|
||||
.FirstOrDefault()
|
||||
?.FileId;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(attachedPhotoFileId))
|
||||
{
|
||||
return attachedPhotoFileId;
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(parsedImageUrl) ? null : parsedImageUrl.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
@@ -136,15 +137,16 @@ public sealed class JoinSessionHandler(
|
||||
transactionCommitted = true;
|
||||
|
||||
// 4. Перерисовываем сообщение
|
||||
var renderResult = SessionBatchRenderer.Render(batchInfo.Title, batchSessions.ToList(), batchParticipants.ToList());
|
||||
var view = SessionBatchViewBuilder.Build(batchInfo.Title, batchSessions.ToList(), batchParticipants.ToList());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await bot.EditMessageText(
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
ct);
|
||||
|
||||
var callbackText = registrationStatus == ParticipantRegistrationStatus.Waitlisted
|
||||
? "Основной состав заполнен. Вы добавлены в лист ожидания."
|
||||
|
||||
@@ -3,6 +3,7 @@ using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
@@ -182,15 +183,16 @@ public sealed class LeaveSessionHandler(
|
||||
await transaction.CommitAsync(ct);
|
||||
transactionCommitted = true;
|
||||
|
||||
var renderResult = SessionBatchRenderer.Render(session.Title, batchSessions, batchParticipants);
|
||||
var view = SessionBatchViewBuilder.Build(session.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await bot.EditMessageText(
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
ct);
|
||||
|
||||
var callbackText = participant.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted
|
||||
? "Вы удалены из листа ожидания."
|
||||
|
||||
@@ -5,40 +5,66 @@ namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
internal sealed record NewSessionParseResult(
|
||||
string? Title,
|
||||
string? Link,
|
||||
string? ImageUrl,
|
||||
int? MaxPlayers,
|
||||
IReadOnlyList<DateTimeOffset> ScheduledTimes,
|
||||
IReadOnlyList<string> PastTimeInputs,
|
||||
IReadOnlyList<string> InvalidTimeInputs,
|
||||
IReadOnlyList<string> InvalidSeatLimitInputs)
|
||||
IReadOnlyList<string> InvalidSeatLimitInputs,
|
||||
IReadOnlyList<string> InvalidRecurringInputs)
|
||||
{
|
||||
public bool IsValid =>
|
||||
!string.IsNullOrWhiteSpace(Title) &&
|
||||
!string.IsNullOrWhiteSpace(Link) &&
|
||||
ScheduledTimes.Count > 0 &&
|
||||
InvalidSeatLimitInputs.Count == 0;
|
||||
InvalidSeatLimitInputs.Count == 0 &&
|
||||
InvalidRecurringInputs.Count == 0;
|
||||
}
|
||||
|
||||
internal static class NewSessionCommandParser
|
||||
{
|
||||
private const int MaxRecurringSessionCount = 52;
|
||||
private const int MaxRecurringIntervalDays = 365;
|
||||
private const string TitlePrefix = "\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435:";
|
||||
private const string TimePrefix = "\u0412\u0440\u0435\u043c\u044f:";
|
||||
private const string LinkPrefix = "\u0421\u0441\u044b\u043b\u043a\u0430:";
|
||||
private static readonly string[] ImagePrefixes =
|
||||
[
|
||||
"\u041a\u0430\u0440\u0442\u0438\u043d\u043a\u0430:",
|
||||
"\u0418\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435:",
|
||||
"\u041e\u0431\u043b\u043e\u0436\u043a\u0430:"
|
||||
];
|
||||
private static readonly string[] SeatLimitPrefixes =
|
||||
[
|
||||
"\u041c\u0435\u0441\u0442:",
|
||||
"\u041b\u0438\u043c\u0438\u0442:",
|
||||
"\u041c\u0430\u043a\u0441\u0438\u043c\u0443\u043c:"
|
||||
];
|
||||
private static readonly string[] RecurringCountPrefixes =
|
||||
[
|
||||
"\u0418\u0433\u0440:",
|
||||
"\u0421\u0435\u0441\u0441\u0438\u0439:",
|
||||
"\u041f\u043e\u0432\u0442\u043e\u0440\u043e\u0432:"
|
||||
];
|
||||
private static readonly string[] RecurringIntervalPrefixes =
|
||||
[
|
||||
"\u0428\u0430\u0433:",
|
||||
"\u0418\u043d\u0442\u0435\u0440\u0432\u0430\u043b:"
|
||||
];
|
||||
|
||||
public static NewSessionParseResult Parse(string? text, DateTimeOffset nowUtc)
|
||||
{
|
||||
string? title = null;
|
||||
string? link = null;
|
||||
string? imageUrl = null;
|
||||
int? maxPlayers = null;
|
||||
int? recurringCount = null;
|
||||
var recurringIntervalDays = 7;
|
||||
var scheduledTimes = new List<DateTimeOffset>();
|
||||
var pastTimeInputs = new List<string>();
|
||||
var invalidTimeInputs = new List<string>();
|
||||
var invalidSeatLimitInputs = new List<string>();
|
||||
var invalidRecurringInputs = new List<string>();
|
||||
|
||||
foreach (var line in (text ?? string.Empty).Split('\n', StringSplitOptions.TrimEntries))
|
||||
{
|
||||
@@ -54,6 +80,14 @@ internal static class NewSessionCommandParser
|
||||
continue;
|
||||
}
|
||||
|
||||
var imagePrefix = ImagePrefixes.FirstOrDefault(prefix =>
|
||||
line.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
||||
if (imagePrefix is not null)
|
||||
{
|
||||
imageUrl = line[imagePrefix.Length..].Trim();
|
||||
continue;
|
||||
}
|
||||
|
||||
var seatLimitPrefix = SeatLimitPrefixes.FirstOrDefault(prefix =>
|
||||
line.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
||||
if (seatLimitPrefix is not null)
|
||||
@@ -71,6 +105,42 @@ internal static class NewSessionCommandParser
|
||||
continue;
|
||||
}
|
||||
|
||||
var recurringCountPrefix = RecurringCountPrefixes.FirstOrDefault(prefix =>
|
||||
line.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
||||
if (recurringCountPrefix is not null)
|
||||
{
|
||||
var recurringInput = line[recurringCountPrefix.Length..].Trim();
|
||||
if (int.TryParse(recurringInput, out var parsedCount) &&
|
||||
parsedCount is >= 1 and <= MaxRecurringSessionCount)
|
||||
{
|
||||
recurringCount = parsedCount;
|
||||
}
|
||||
else
|
||||
{
|
||||
invalidRecurringInputs.Add(recurringInput);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var recurringIntervalPrefix = RecurringIntervalPrefixes.FirstOrDefault(prefix =>
|
||||
line.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
||||
if (recurringIntervalPrefix is not null)
|
||||
{
|
||||
var recurringInput = line[recurringIntervalPrefix.Length..].Trim();
|
||||
if (int.TryParse(recurringInput, out var parsedInterval) &&
|
||||
parsedInterval is >= 1 and <= MaxRecurringIntervalDays)
|
||||
{
|
||||
recurringIntervalDays = parsedInterval;
|
||||
}
|
||||
else
|
||||
{
|
||||
invalidRecurringInputs.Add(recurringInput);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line.StartsWith(TimePrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
@@ -92,13 +162,23 @@ internal static class NewSessionCommandParser
|
||||
scheduledTimes.Add(scheduledAt);
|
||||
}
|
||||
|
||||
if (recurringCount.HasValue && scheduledTimes.Count == 1)
|
||||
{
|
||||
var firstScheduledTime = scheduledTimes[0];
|
||||
scheduledTimes = Enumerable.Range(0, recurringCount.Value)
|
||||
.Select(index => firstScheduledTime.AddDays(recurringIntervalDays * index))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
return new NewSessionParseResult(
|
||||
title,
|
||||
link,
|
||||
imageUrl,
|
||||
maxPlayers,
|
||||
scheduledTimes,
|
||||
pastTimeInputs,
|
||||
invalidTimeInputs,
|
||||
invalidSeatLimitInputs);
|
||||
invalidSeatLimitInputs,
|
||||
invalidRecurringInputs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
@@ -13,7 +14,7 @@ public sealed record PromoteWaitlistedPlayerCommand(
|
||||
long ChatId,
|
||||
int MessageId);
|
||||
|
||||
internal sealed record PromoteWaitlistSessionDto(string Title, Guid BatchId, long GmId, int? MaxPlayers);
|
||||
internal sealed record PromoteWaitlistSessionDto(string Title, Guid BatchId, int? BatchMessageId, bool CanManage, int? MaxPlayers);
|
||||
internal sealed record WaitlistedParticipantDto(Guid ParticipantRowId, string DisplayName);
|
||||
|
||||
public sealed class PromoteWaitlistedPlayerHandler(
|
||||
@@ -33,14 +34,20 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
"""
|
||||
SELECT s.title AS Title,
|
||||
s.batch_id AS BatchId,
|
||||
s.batch_message_id AS BatchMessageId,
|
||||
s.max_players AS MaxPlayers,
|
||||
g.gm_telegram_id AS GmId
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND p.telegram_id = @TelegramUserId
|
||||
) AS CanManage
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
WHERE s.id = @SessionId
|
||||
FOR UPDATE
|
||||
""",
|
||||
new { command.SessionId },
|
||||
new { command.SessionId, command.TelegramUserId },
|
||||
transaction);
|
||||
|
||||
if (session is null)
|
||||
@@ -50,10 +57,10 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.GmId != command.TelegramUserId)
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только Мастер Игры (GM) может поднимать игроков из листа ожидания.", showAlert: true, cancellationToken: ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только owner или co-GM может поднимать игроков из листа ожидания.", showAlert: true, cancellationToken: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -156,15 +163,16 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
await transaction.CommitAsync(ct);
|
||||
transactionCommitted = true;
|
||||
|
||||
var renderResult = SessionBatchRenderer.Render(session.Title, batchSessions, batchParticipants);
|
||||
var view = SessionBatchViewBuilder.Build(session.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await bot.EditMessageText(
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
messageId: session.BatchMessageId ?? command.MessageId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
ct);
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, $"{promoted.DisplayName} переведен(а) в основной состав.", cancellationToken: ct);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.ExportCalendar;
|
||||
|
||||
@@ -11,20 +13,21 @@ internal sealed record CalendarSessionDto(Guid Id, string Title, DateTime Schedu
|
||||
|
||||
public sealed class ExportCalendarHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient botClient)
|
||||
ITelegramBotClient botClient,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
public async Task HandleAsync(Message message, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);
|
||||
|
||||
var sessions = await connection.QueryAsync<CalendarSessionDto>(
|
||||
@"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
WHERE g.telegram_chat_id = @ChatId
|
||||
AND s.status = @Planned
|
||||
AND s.scheduled_at > NOW()
|
||||
ORDER BY s.scheduled_at ASC",
|
||||
@"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt"
|
||||
+ " FROM sessions s"
|
||||
+ " JOIN game_groups g ON s.group_id = g.id"
|
||||
+ " WHERE g.telegram_chat_id = @ChatId"
|
||||
+ " AND s.status = @Planned"
|
||||
+ " AND s.scheduled_at > NOW()"
|
||||
+ " ORDER BY s.scheduled_at ASC",
|
||||
new { ChatId = message.Chat.Id, Planned = SessionStatus.Planned });
|
||||
|
||||
var sessionsList = sessions.ToList();
|
||||
@@ -54,8 +57,6 @@ public sealed class ExportCalendarHandler(
|
||||
sb.AppendLine($"DTSTART:{dtStart}");
|
||||
sb.AppendLine($"DTEND:{dtEnd}");
|
||||
sb.AppendLine($"SUMMARY:{s.Title}");
|
||||
// Escape special chars according to iCal standards (RFC 5545) -- simple escaping for summary
|
||||
// In a fuller implementation we'd escape \r\n, commas, etc. But titles are mostly plain text.
|
||||
sb.AppendLine("END:VEVENT");
|
||||
}
|
||||
|
||||
@@ -66,11 +67,45 @@ public sealed class ExportCalendarHandler(
|
||||
|
||||
var inputFile = InputFile.FromStream(stream, "schedule.ics");
|
||||
|
||||
// Create calendar subscription
|
||||
string? subscriptionUrl = null;
|
||||
var baseUrl = configuration["Web:BaseUrl"];
|
||||
var senderId = message.From?.Id;
|
||||
if (!string.IsNullOrWhiteSpace(baseUrl) && senderId.HasValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var token = Guid.NewGuid().ToString("N");
|
||||
var groupId = await connection.QueryFirstOrDefaultAsync<Guid?>(
|
||||
@"SELECT id FROM game_groups WHERE telegram_chat_id = @ChatId",
|
||||
new { ChatId = message.Chat.Id });
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
@"INSERT INTO calendar_subscriptions (id, token, user_telegram_id, group_id, filter_type, created_at, expires_at)
|
||||
VALUES (gen_random_uuid(), @token, @userTelegramId, @groupId, @filterType, now(), NULL)",
|
||||
new { token, userTelegramId = senderId.Value, groupId, filterType = (int)CalendarSubscriptionFilter.SpecificGroup });
|
||||
|
||||
subscriptionUrl = $"{baseUrl.TrimEnd('/')}/calendar/{token}.ics";
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Non-critical: if subscription creation fails, still send the file
|
||||
}
|
||||
}
|
||||
|
||||
var replyMarkup = subscriptionUrl is not null
|
||||
? new InlineKeyboardMarkup(new[]
|
||||
{
|
||||
new[] { InlineKeyboardButton.WithUrl("🔗 Подписаться на календарь", subscriptionUrl) }
|
||||
})
|
||||
: null;
|
||||
|
||||
await botClient.SendDocument(
|
||||
chatId: message.Chat.Id,
|
||||
document: inputFile,
|
||||
caption: "📅 <b>Ваш календарь игр!</b>\nОткройте файл на устройстве, чтобы добавить события в свой календарь.",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: replyMarkup,
|
||||
messageThreadId: message.MessageThreadId,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ public sealed record DeleteSessionCommand(
|
||||
long ChatId,
|
||||
int MessageId);
|
||||
|
||||
internal sealed record DeleteSessionInfoDto(string Title, Guid BatchId, long GmId, int? ThreadId);
|
||||
internal sealed record DeleteSessionInfoDto(string Title, Guid BatchId, bool CanManage, int? ThreadId);
|
||||
|
||||
public sealed class DeleteSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
@@ -24,13 +24,23 @@ public sealed class DeleteSessionHandler(
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
await using var transaction = await connection.BeginTransactionAsync(ct);
|
||||
|
||||
// 1. Fetch session and verify GM
|
||||
// 1. Fetch session and verify group manager.
|
||||
var session = await connection.QuerySingleOrDefaultAsync<DeleteSessionInfoDto>(
|
||||
@"SELECT s.title as Title, s.batch_id as BatchId, s.thread_id as ThreadId, g.gm_telegram_id as GmId
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
WHERE s.id = @SessionId",
|
||||
new { command.SessionId }, transaction);
|
||||
"""
|
||||
SELECT s.title AS Title,
|
||||
s.batch_id AS BatchId,
|
||||
s.thread_id AS ThreadId,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND p.telegram_id = @TelegramUserId
|
||||
) AS CanManage
|
||||
FROM sessions s
|
||||
WHERE s.id = @SessionId
|
||||
""",
|
||||
new { command.SessionId, command.TelegramUserId }, transaction);
|
||||
|
||||
if (session == null)
|
||||
{
|
||||
@@ -38,9 +48,9 @@ public sealed class DeleteSessionHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.GmId != command.TelegramUserId)
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только Мастер Игры (GM) может удалять сессию.", showAlert: true, cancellationToken: ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только owner или co-GM может удалять сессию.", showAlert: true, cancellationToken: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -77,16 +87,23 @@ public sealed class DeleteSessionHandler(
|
||||
@"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt, s.status as Status, s.max_players as MaxPlayers,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Active) as PlayerCount,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Waitlisted) as WaitlistCount,
|
||||
g.gm_telegram_id as GmId
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players manager_player ON manager_player.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND manager_player.telegram_id = @TelegramUserId
|
||||
) AS CanManage
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
LEFT JOIN session_participants sp ON s.id = sp.session_id
|
||||
WHERE g.telegram_chat_id = @ChatId AND s.status != @Cancelled AND s.scheduled_at > NOW()
|
||||
GROUP BY s.id, s.title, s.scheduled_at, s.status, s.max_players, g.gm_telegram_id
|
||||
GROUP BY s.id, s.title, s.scheduled_at, s.status, s.max_players, s.group_id
|
||||
ORDER BY s.scheduled_at ASC",
|
||||
new
|
||||
{
|
||||
ChatId = command.ChatId,
|
||||
command.TelegramUserId,
|
||||
Cancelled = SessionStatus.Cancelled,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Waitlisted = ParticipantRegistrationStatus.Waitlisted
|
||||
@@ -100,30 +117,16 @@ public sealed class DeleteSessionHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
var text = "📅 <b>Ближайшие игры:</b>\n\n";
|
||||
foreach (var s in sessionsList)
|
||||
{
|
||||
var seats = s.MaxPlayers.HasValue
|
||||
? $"{s.PlayerCount}/{s.MaxPlayers.Value}"
|
||||
: s.PlayerCount.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var waitlist = s.WaitlistCount > 0 ? $", ожидание: {s.WaitlistCount}" : string.Empty;
|
||||
text += $"🔹 <b>{s.ScheduledAt.FormatMoscow()}</b> — {System.Net.WebUtility.HtmlEncode(s.Title)} (Места: {seats}{waitlist})\n";
|
||||
}
|
||||
|
||||
var isGm = command.TelegramUserId == sessionsList.First().GmId;
|
||||
var keyboard = isGm
|
||||
? new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
|
||||
sessionsList.Select(s => new[] { Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData($"🗑 Удалить {s.ScheduledAt.FormatMoscowShort()}", $"delete_session:{s.Id}") }))
|
||||
: null;
|
||||
var renderResult = SessionListMessageRenderer.Render(sessionsList);
|
||||
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
command.ChatId,
|
||||
command.MessageId,
|
||||
text,
|
||||
renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: keyboard,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -3,10 +3,59 @@ using GmRelay.Shared.Domain;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.ListSessions;
|
||||
|
||||
internal sealed record SessionListItemDto(Guid Id, string Title, DateTime ScheduledAt, string Status, int? MaxPlayers, int PlayerCount, int WaitlistCount, long GmId);
|
||||
internal sealed record SessionListItemDto(Guid Id, string Title, DateTime ScheduledAt, string Status, int? MaxPlayers, int PlayerCount, int WaitlistCount, bool CanManage);
|
||||
|
||||
internal static class SessionListMessageRenderer
|
||||
{
|
||||
public static (string Text, InlineKeyboardMarkup? Markup) Render(IReadOnlyList<SessionListItemDto> sessions)
|
||||
{
|
||||
var text = "📅 <b>Ближайшие игры:</b>\n\n";
|
||||
foreach (var session in sessions)
|
||||
{
|
||||
var seats = session.MaxPlayers.HasValue
|
||||
? $"{session.PlayerCount}/{session.MaxPlayers.Value}"
|
||||
: session.PlayerCount.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var waitlist = session.WaitlistCount > 0 ? $", ожидание: {session.WaitlistCount}" : string.Empty;
|
||||
text += $"🔹 <b>{session.ScheduledAt.FormatMoscow()}</b> — {System.Net.WebUtility.HtmlEncode(session.Title)} (Места: {seats}{waitlist})\n";
|
||||
}
|
||||
|
||||
var canManage = sessions.Count > 0 && sessions.First().CanManage;
|
||||
if (!canManage)
|
||||
{
|
||||
return (text, null);
|
||||
}
|
||||
|
||||
var buttons = new List<InlineKeyboardButton[]>();
|
||||
foreach (var session in sessions)
|
||||
{
|
||||
var dateTitle = session.ScheduledAt.FormatMoscowShort();
|
||||
buttons.Add(
|
||||
[
|
||||
InlineKeyboardButton.WithCallbackData($"❌ {dateTitle}", $"cancel_session:{session.Id}"),
|
||||
InlineKeyboardButton.WithCallbackData($"⏰ {dateTitle}", $"reschedule_session:{session.Id}")
|
||||
]);
|
||||
|
||||
if (SessionCapacityRules.CanPromoteWaitlistedPlayer(session.MaxPlayers, session.PlayerCount, session.WaitlistCount))
|
||||
{
|
||||
buttons.Add(
|
||||
[
|
||||
InlineKeyboardButton.WithCallbackData($"⬆️ Из ожидания {dateTitle}", $"promote_waitlist:{session.Id}")
|
||||
]);
|
||||
}
|
||||
|
||||
buttons.Add(
|
||||
[
|
||||
InlineKeyboardButton.WithCallbackData($"🗑 Удалить {dateTitle}", $"delete_session:{session.Id}")
|
||||
]);
|
||||
}
|
||||
|
||||
return (text, new InlineKeyboardMarkup(buttons));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ListSessionsHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
@@ -20,16 +69,23 @@ public sealed class ListSessionsHandler(
|
||||
@"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt, s.status as Status, s.max_players as MaxPlayers,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Active) as PlayerCount,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Waitlisted) as WaitlistCount,
|
||||
g.gm_telegram_id as GmId
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players manager_player ON manager_player.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND manager_player.telegram_id = @TelegramUserId
|
||||
) AS CanManage
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
LEFT JOIN session_participants sp ON s.id = sp.session_id
|
||||
WHERE g.telegram_chat_id = @ChatId AND s.status != @Cancelled AND s.scheduled_at > NOW()
|
||||
GROUP BY s.id, s.title, s.scheduled_at, s.status, s.max_players, g.gm_telegram_id
|
||||
GROUP BY s.id, s.title, s.scheduled_at, s.status, s.max_players, s.group_id
|
||||
ORDER BY s.scheduled_at ASC",
|
||||
new
|
||||
{
|
||||
ChatId = message.Chat.Id,
|
||||
TelegramUserId = message.From?.Id,
|
||||
Cancelled = SessionStatus.Cancelled,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Waitlisted = ParticipantRegistrationStatus.Waitlisted
|
||||
@@ -46,27 +102,13 @@ public sealed class ListSessionsHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
var text = "📅 <b>Ближайшие игры:</b>\n\n";
|
||||
foreach (var s in sessionsList)
|
||||
{
|
||||
var seats = s.MaxPlayers.HasValue
|
||||
? $"{s.PlayerCount}/{s.MaxPlayers.Value}"
|
||||
: s.PlayerCount.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var waitlist = s.WaitlistCount > 0 ? $", ожидание: {s.WaitlistCount}" : string.Empty;
|
||||
text += $"🔹 <b>{s.ScheduledAt.FormatMoscow()}</b> — {System.Net.WebUtility.HtmlEncode(s.Title)} (Места: {seats}{waitlist})\n";
|
||||
}
|
||||
|
||||
var isGm = message.From?.Id == sessionsList.First().GmId;
|
||||
var keyboard = isGm
|
||||
? new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
|
||||
sessionsList.Select(s => new[] { Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData($"🗑 Удалить {s.ScheduledAt.FormatMoscowShort()}", $"delete_session:{s.Id}") }))
|
||||
: null;
|
||||
var renderResult = SessionListMessageRenderer.Render(sessionsList);
|
||||
|
||||
await botClient.SendMessage(
|
||||
chatId: message.Chat.Id,
|
||||
text: text,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: keyboard,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
+187
-46
@@ -1,10 +1,12 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
|
||||
@@ -12,20 +14,26 @@ namespace GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
|
||||
internal sealed record AwaitingProposalDto(
|
||||
Guid Id, Guid SessionId, string Title, DateTime CurrentScheduledAt,
|
||||
Guid BatchId, int? BatchMessageId, long TelegramChatId);
|
||||
Guid BatchId, int? BatchMessageId, long TelegramChatId, string NotificationMode);
|
||||
|
||||
internal sealed record VoteParticipantDto(Guid PlayerId, string DisplayName, string? TelegramUsername);
|
||||
internal sealed record VoteParticipantDto(
|
||||
Guid PlayerId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
long TelegramId = 0);
|
||||
|
||||
// ── Handler ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Handles text input from the GM who has an AwaitingTime proposal.
|
||||
/// Parses the new time, creates a voting message, and tags all participants.
|
||||
/// Parses reschedule options with a voting deadline, creates a voting message,
|
||||
/// and tags all participants.
|
||||
/// If no participants are registered, reschedules immediately.
|
||||
/// </summary>
|
||||
public sealed class HandleRescheduleTimeInputHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<HandleRescheduleTimeInputHandler> logger)
|
||||
{
|
||||
/// <summary>
|
||||
@@ -48,13 +56,21 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
"""
|
||||
SELECT rp.id AS Id, rp.session_id AS SessionId, s.title AS Title, s.scheduled_at AS CurrentScheduledAt,
|
||||
s.batch_id AS BatchId, s.batch_message_id AS BatchMessageId,
|
||||
g.telegram_chat_id AS TelegramChatId
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM reschedule_proposals rp
|
||||
JOIN sessions s ON s.id = rp.session_id
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE rp.proposed_by = @GmId
|
||||
AND rp.status = 'AwaitingTime'
|
||||
AND g.telegram_chat_id = @ChatId
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players manager_player ON manager_player.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND manager_player.telegram_id = @GmId
|
||||
)
|
||||
ORDER BY rp.created_at DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
@@ -63,30 +79,24 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
if (proposal is null)
|
||||
return false;
|
||||
|
||||
// 2. Parse the new time
|
||||
if (!MoscowTime.TryParseMoscow(text, out var newTime))
|
||||
// 2. Parse voting input
|
||||
if (!RescheduleVotingInput.TryParse(text, DateTimeOffset.UtcNow, out var votingInput, out var parseError))
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
text: "⚠️ Не удалось распознать время. Используйте формат: <code>ДД.ММ.ГГГГ ЧЧ:ММ</code>\nНапример: <code>25.04.2026 19:30</code>",
|
||||
text: $"⚠️ {parseError}\n\nИспользуйте формат:\n<code>25.04.2026 19:30\n26.04.2026 18:00\nДедлайн: 25.04.2026 12:00</code>",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (newTime <= DateTimeOffset.UtcNow)
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
text: "⚠️ Новое время должно быть в будущем. Попробуйте снова.",
|
||||
cancellationToken: ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. Load participants (non-GM) signed up for this session
|
||||
var participants = (await connection.QueryAsync<VoteParticipantDto>(
|
||||
"""
|
||||
SELECT p.id AS PlayerId, p.display_name AS DisplayName, p.telegram_username AS TelegramUsername
|
||||
SELECT p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
p.telegram_id AS TelegramId
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
@@ -98,35 +108,56 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
// 4. If no participants — reschedule immediately
|
||||
if (participants.Count == 0)
|
||||
{
|
||||
await RescheduleImmediately(connection, proposal, newTime, chatId, ct);
|
||||
await RescheduleImmediately(connection, proposal, votingInput.Options[0], chatId, ct);
|
||||
await TryDeleteMessage(chatId, message.MessageId, ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 5. Create voting message
|
||||
await using var transaction = await connection.BeginTransactionAsync(ct);
|
||||
var options = votingInput.Options
|
||||
.Select((proposedAt, index) => new RescheduleOptionDto(
|
||||
Guid.NewGuid(),
|
||||
index + 1,
|
||||
proposedAt))
|
||||
.ToList();
|
||||
|
||||
// Update proposal with proposed time and Voting status
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE reschedule_proposals
|
||||
SET proposed_at = @ProposedAt, status = 'Voting', vote_chat_id = @ChatId
|
||||
SET voting_deadline_at = @Deadline, status = 'Voting', vote_chat_id = @ChatId
|
||||
WHERE id = @Id
|
||||
""",
|
||||
new { ProposedAt = newTime, ChatId = chatId, Id = proposal.Id },
|
||||
new { votingInput.Deadline, ChatId = chatId, Id = proposal.Id },
|
||||
transaction);
|
||||
|
||||
foreach (var option in options)
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO reschedule_options (id, proposal_id, proposed_at, display_order)
|
||||
VALUES (@OptionId, @ProposalId, @ProposedAt, @DisplayOrder)
|
||||
""",
|
||||
new
|
||||
{
|
||||
option.OptionId,
|
||||
ProposalId = proposal.Id,
|
||||
option.ProposedAt,
|
||||
option.DisplayOrder
|
||||
},
|
||||
transaction);
|
||||
}
|
||||
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
// Build voting message text
|
||||
var voteText = BuildVotingMessage(proposal.Title, proposal.CurrentScheduledAt, newTime, participants, []);
|
||||
|
||||
var keyboard = new InlineKeyboardMarkup([
|
||||
[
|
||||
InlineKeyboardButton.WithCallbackData("✅ Согласен", $"reschedule_vote:yes:{proposal.Id}"),
|
||||
InlineKeyboardButton.WithCallbackData("❌ Против", $"reschedule_vote:no:{proposal.Id}")
|
||||
]
|
||||
]);
|
||||
var voteText = BuildVotingMessage(
|
||||
proposal.Title,
|
||||
proposal.CurrentScheduledAt,
|
||||
votingInput.Deadline,
|
||||
options,
|
||||
participants,
|
||||
[]);
|
||||
var keyboard = BuildVotingKeyboard(options);
|
||||
|
||||
var voteMsg = await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
@@ -135,12 +166,46 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
replyMarkup: keyboard,
|
||||
cancellationToken: ct);
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(proposal.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
var optionsText = string.Join(
|
||||
"\n",
|
||||
options.Select(option => $"{option.DisplayOrder}. <b>{option.ProposedAt.FormatMoscow()}</b> (МСК)"));
|
||||
var directText = $"""
|
||||
🔄 <b>Голосование за перенос сессии</b>
|
||||
|
||||
📌 <b>{System.Net.WebUtility.HtmlEncode(proposal.Title)}</b>
|
||||
📅 Текущее время: <b>{proposal.CurrentScheduledAt.FormatMoscow()}</b> (МСК)
|
||||
🗳 Варианты:
|
||||
{optionsText}
|
||||
|
||||
⏳ Дедлайн: <b>{votingInput.Deadline.FormatMoscow()}</b> (МСК)
|
||||
|
||||
Проголосуйте кнопкой в групповом сообщении.
|
||||
""";
|
||||
|
||||
await directSender.SendAsync(
|
||||
participants.Select(p => new DirectNotificationRecipient(
|
||||
p.TelegramId,
|
||||
p.DisplayName)),
|
||||
directText,
|
||||
"reschedule-vote",
|
||||
proposal.SessionId,
|
||||
ct);
|
||||
}
|
||||
|
||||
// Store vote message ID
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE reschedule_proposals SET vote_message_id = @MsgId WHERE id = @Id",
|
||||
new { MsgId = voteMsg.MessageId, Id = proposal.Id });
|
||||
|
||||
logger.LogInformation("Reschedule voting started for session {SessionId}, proposal {ProposalId}", proposal.SessionId, proposal.Id);
|
||||
logger.LogInformation(
|
||||
"Reschedule voting started for session {SessionId}, proposal {ProposalId}, options {OptionCount}, deadline {Deadline}",
|
||||
proposal.SessionId,
|
||||
proposal.Id,
|
||||
options.Count,
|
||||
votingInput.Deadline);
|
||||
|
||||
// Delete GM's time input message
|
||||
await TryDeleteMessage(chatId, message.MessageId, ct);
|
||||
@@ -156,7 +221,11 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE sessions SET scheduled_at = @NewTime, status = @Status, updated_at = now()
|
||||
UPDATE sessions
|
||||
SET scheduled_at = @NewTime,
|
||||
status = @Status,
|
||||
one_hour_reminder_processed_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE id = @SessionId
|
||||
""",
|
||||
new { NewTime = newTime, proposal.SessionId, Status = SessionStatus.Planned },
|
||||
@@ -182,33 +251,105 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
}
|
||||
|
||||
internal static string BuildVotingMessage(
|
||||
string title, DateTime currentTime, DateTimeOffset newTime,
|
||||
string title,
|
||||
DateTime currentTime,
|
||||
DateTimeOffset deadline,
|
||||
IReadOnlyList<RescheduleOptionDto> options,
|
||||
IReadOnlyList<VoteParticipantDto> participants,
|
||||
IReadOnlyCollection<Guid> approvedPlayerIds)
|
||||
IReadOnlyList<RescheduleOptionVoteDto> votes)
|
||||
{
|
||||
var votesByOption = votes
|
||||
.GroupBy(v => v.OptionId)
|
||||
.ToDictionary(g => g.Key, g => g.ToList());
|
||||
var votedPlayerIds = votes.Select(v => v.PlayerId).ToHashSet();
|
||||
var pendingParticipants = participants
|
||||
.Where(p => !votedPlayerIds.Contains(p.PlayerId))
|
||||
.Select(FormatParticipantName)
|
||||
.ToList();
|
||||
|
||||
var lines = new List<string>
|
||||
{
|
||||
$"🔄 <b>Перенос сессии «{System.Net.WebUtility.HtmlEncode(title)}»</b>",
|
||||
"",
|
||||
$"📅 Текущее время: <b>{currentTime.FormatMoscow()}</b> (МСК)",
|
||||
$"📅 Новое время: <b>{newTime.ToOffset(TimeSpan.FromHours(3)).ToString("d MMMM yyyy, HH:mm", System.Globalization.CultureInfo.GetCultureInfo("ru-RU"))}</b> (МСК)",
|
||||
$"⏳ Дедлайн: <b>{deadline.FormatMoscow()}</b> (МСК)",
|
||||
"",
|
||||
"Для переноса нужно согласие всех участников:"
|
||||
"Выберите один из вариантов:"
|
||||
};
|
||||
|
||||
foreach (var p in participants)
|
||||
foreach (var option in options.OrderBy(x => x.DisplayOrder))
|
||||
{
|
||||
var name = p.TelegramUsername is not null ? $"@{p.TelegramUsername}" : p.DisplayName;
|
||||
var icon = approvedPlayerIds.Contains(p.PlayerId) ? "✅" : "⏳";
|
||||
lines.Add($" {icon} {name}");
|
||||
var optionVotes = votesByOption.GetValueOrDefault(option.OptionId, []);
|
||||
lines.Add(
|
||||
$"{option.DisplayOrder}. <b>{option.ProposedAt.FormatMoscow()}</b> (МСК) — {FormatVoteCount(optionVotes.Count)}");
|
||||
|
||||
if (optionVotes.Count > 0)
|
||||
{
|
||||
lines.Add($" {string.Join(", ", optionVotes.Select(FormatParticipantName))}");
|
||||
}
|
||||
}
|
||||
|
||||
if (pendingParticipants.Count > 0)
|
||||
{
|
||||
lines.Add("");
|
||||
lines.Add($"Не проголосовали: {string.Join(", ", pendingParticipants)}");
|
||||
}
|
||||
|
||||
lines.Add("");
|
||||
lines.Add($"Голоса: {approvedPlayerIds.Count}/{participants.Count} ✅");
|
||||
lines.Add($"Голосов: {votedPlayerIds.Count}/{participants.Count}");
|
||||
lines.Add("Правило: побеждает вариант с большинством голосов к дедлайну; при ничьей перенос не применяется.");
|
||||
|
||||
return string.Join("\n", lines);
|
||||
}
|
||||
|
||||
internal static InlineKeyboardMarkup BuildVotingKeyboard(IReadOnlyList<RescheduleOptionDto> options)
|
||||
{
|
||||
return new InlineKeyboardMarkup(
|
||||
options
|
||||
.OrderBy(option => option.DisplayOrder)
|
||||
.Select(option => new[]
|
||||
{
|
||||
InlineKeyboardButton.WithCallbackData(
|
||||
$"{option.DisplayOrder}. {FormatButtonTime(option.ProposedAt)}",
|
||||
$"reschedule_vote:{option.OptionId}")
|
||||
}));
|
||||
}
|
||||
|
||||
internal static string FormatParticipantName(VoteParticipantDto participant)
|
||||
{
|
||||
return participant.TelegramUsername is { Length: > 0 } username
|
||||
? $"@{System.Net.WebUtility.HtmlEncode(username)}"
|
||||
: System.Net.WebUtility.HtmlEncode(participant.DisplayName);
|
||||
}
|
||||
|
||||
internal static string FormatParticipantName(RescheduleOptionVoteDto vote)
|
||||
{
|
||||
return vote.TelegramUsername is { Length: > 0 } username
|
||||
? $"@{System.Net.WebUtility.HtmlEncode(username)}"
|
||||
: System.Net.WebUtility.HtmlEncode(vote.DisplayName);
|
||||
}
|
||||
|
||||
private static string FormatVoteCount(int count)
|
||||
{
|
||||
var modulo100 = count % 100;
|
||||
var modulo10 = count % 10;
|
||||
var word = modulo100 is >= 11 and <= 14
|
||||
? "голосов"
|
||||
: modulo10 switch
|
||||
{
|
||||
1 => "голос",
|
||||
>= 2 and <= 4 => "голоса",
|
||||
_ => "голосов"
|
||||
};
|
||||
|
||||
return $"{count} {word}";
|
||||
}
|
||||
|
||||
private static string FormatButtonTime(DateTimeOffset utc)
|
||||
=> utc.ToOffset(TimeSpan.FromHours(3)).ToString(
|
||||
"dd.MM HH:mm",
|
||||
System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
private async Task TryUpdateBatchMessage(AwaitingProposalDto proposal, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -235,16 +376,16 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
|
||||
if (proposal.BatchMessageId.HasValue)
|
||||
{
|
||||
var renderResult = SessionBatchRenderer.Render(
|
||||
proposal.Title, batchSessions, batchParticipants);
|
||||
var view = SessionBatchViewBuilder.Build(proposal.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await bot.EditMessageText(
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageId: proposal.BatchMessageId.Value,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
+89
-222
@@ -1,15 +1,12 @@
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
|
||||
public sealed record HandleRescheduleVoteCommand(
|
||||
Guid ProposalId,
|
||||
string Vote,
|
||||
Guid OptionId,
|
||||
long TelegramUserId,
|
||||
string CallbackQueryId,
|
||||
long ChatId,
|
||||
@@ -18,14 +15,9 @@ public sealed record HandleRescheduleVoteCommand(
|
||||
internal sealed record VoteProposalDto(
|
||||
Guid Id,
|
||||
Guid SessionId,
|
||||
DateTime ProposedAt,
|
||||
DateTimeOffset VotingDeadlineAt,
|
||||
string Title,
|
||||
DateTime CurrentScheduledAt,
|
||||
Guid BatchId,
|
||||
string SessionStatus,
|
||||
long TelegramChatId,
|
||||
int? ConfirmationMessageId,
|
||||
int? BatchMessageId);
|
||||
DateTime CurrentScheduledAt);
|
||||
|
||||
public sealed class HandleRescheduleVoteHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
@@ -41,20 +33,15 @@ public sealed class HandleRescheduleVoteHandler(
|
||||
"""
|
||||
SELECT rp.id AS Id,
|
||||
rp.session_id AS SessionId,
|
||||
rp.proposed_at AS ProposedAt,
|
||||
rp.voting_deadline_at AS VotingDeadlineAt,
|
||||
s.title AS Title,
|
||||
s.scheduled_at AS CurrentScheduledAt,
|
||||
s.batch_id AS BatchId,
|
||||
s.status AS SessionStatus,
|
||||
s.confirmation_message_id AS ConfirmationMessageId,
|
||||
s.batch_message_id AS BatchMessageId,
|
||||
g.telegram_chat_id AS TelegramChatId
|
||||
FROM reschedule_proposals rp
|
||||
s.scheduled_at AS CurrentScheduledAt
|
||||
FROM reschedule_options ro
|
||||
JOIN reschedule_proposals rp ON rp.id = ro.proposal_id
|
||||
JOIN sessions s ON s.id = rp.session_id
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE rp.id = @ProposalId AND rp.status = 'Voting'
|
||||
WHERE ro.id = @OptionId AND rp.status = 'Voting'
|
||||
""",
|
||||
new { command.ProposalId },
|
||||
new { command.OptionId },
|
||||
transaction);
|
||||
|
||||
if (proposal is null)
|
||||
@@ -66,6 +53,16 @@ public sealed class HandleRescheduleVoteHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
if (proposal.VotingDeadlineAt <= DateTimeOffset.UtcNow)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(
|
||||
command.CallbackQueryId,
|
||||
"Дедлайн уже прошёл. Результаты скоро будут применены.",
|
||||
showAlert: true,
|
||||
cancellationToken: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var playerId = await connection.ExecuteScalarAsync<Guid?>(
|
||||
"""
|
||||
SELECT p.id
|
||||
@@ -90,221 +87,91 @@ public sealed class HandleRescheduleVoteHandler(
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO reschedule_votes (proposal_id, player_id, vote)
|
||||
VALUES (@ProposalId, @PlayerId, @Vote)
|
||||
INSERT INTO reschedule_option_votes (proposal_id, player_id, option_id)
|
||||
VALUES (@ProposalId, @PlayerId, @OptionId)
|
||||
ON CONFLICT (proposal_id, player_id) DO UPDATE
|
||||
SET vote = EXCLUDED.vote,
|
||||
SET option_id = EXCLUDED.option_id,
|
||||
voted_at = now()
|
||||
""",
|
||||
new { command.ProposalId, PlayerId = playerId.Value, command.Vote },
|
||||
new
|
||||
{
|
||||
ProposalId = proposal.Id,
|
||||
PlayerId = playerId.Value,
|
||||
command.OptionId
|
||||
},
|
||||
transaction);
|
||||
|
||||
var participants = command.Vote.Equals("no", StringComparison.OrdinalIgnoreCase)
|
||||
? new List<VoteParticipantDto>()
|
||||
: (await connection.QueryAsync<VoteParticipantDto>(
|
||||
"""
|
||||
SELECT p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
""",
|
||||
new { proposal.SessionId, Active = ParticipantRegistrationStatus.Active },
|
||||
transaction)).ToList();
|
||||
var participants = (await connection.QueryAsync<VoteParticipantDto>(
|
||||
"""
|
||||
SELECT p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
p.telegram_id AS TelegramId
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
ORDER BY p.display_name
|
||||
""",
|
||||
new { proposal.SessionId, Active = ParticipantRegistrationStatus.Active },
|
||||
transaction)).ToList();
|
||||
|
||||
var approvedPlayerIds = command.Vote.Equals("no", StringComparison.OrdinalIgnoreCase)
|
||||
? new HashSet<Guid>()
|
||||
: (await connection.QueryAsync<Guid>(
|
||||
"""
|
||||
SELECT player_id
|
||||
FROM reschedule_votes
|
||||
WHERE proposal_id = @ProposalId AND vote = 'yes'
|
||||
""",
|
||||
new { command.ProposalId },
|
||||
transaction)).ToHashSet();
|
||||
var options = (await connection.QueryAsync<RescheduleOptionDto>(
|
||||
"""
|
||||
SELECT id AS OptionId,
|
||||
display_order AS DisplayOrder,
|
||||
proposed_at AS ProposedAt
|
||||
FROM reschedule_options
|
||||
WHERE proposal_id = @ProposalId
|
||||
ORDER BY display_order
|
||||
""",
|
||||
new { ProposalId = proposal.Id },
|
||||
transaction)).ToList();
|
||||
|
||||
var decision = RescheduleVoteRules.Evaluate(command.Vote, participants.Count, approvedPlayerIds.Count);
|
||||
var votes = (await connection.QueryAsync<RescheduleOptionVoteDto>(
|
||||
"""
|
||||
SELECT rov.option_id AS OptionId,
|
||||
p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername
|
||||
FROM reschedule_option_votes rov
|
||||
JOIN players p ON p.id = rov.player_id
|
||||
WHERE rov.proposal_id = @ProposalId
|
||||
ORDER BY rov.voted_at, p.display_name
|
||||
""",
|
||||
new { ProposalId = proposal.Id },
|
||||
transaction)).ToList();
|
||||
|
||||
if (decision.Outcome == RescheduleVoteOutcome.Rejected)
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE reschedule_proposals SET status = 'Rejected' WHERE id = @Id",
|
||||
new { Id = command.ProposalId },
|
||||
transaction);
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
await transaction.CommitAsync(ct);
|
||||
var voteText = HandleRescheduleTimeInputHandler.BuildVotingMessage(
|
||||
proposal.Title,
|
||||
proposal.CurrentScheduledAt,
|
||||
proposal.VotingDeadlineAt,
|
||||
options,
|
||||
participants,
|
||||
votes);
|
||||
var keyboard = HandleRescheduleTimeInputHandler.BuildVotingKeyboard(options);
|
||||
|
||||
var voterName = await connection.QuerySingleOrDefaultAsync<string>(
|
||||
"SELECT display_name FROM players WHERE telegram_id = @TelegramUserId",
|
||||
new { command.TelegramUserId });
|
||||
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: $"❌ <b>Перенос сессии «{System.Net.WebUtility.HtmlEncode(proposal.Title)}» отклонён!</b>\n\n{voterName ?? "Участник"} проголосовал(а) против. Время сессии остаётся прежним:\n📅 <b>{proposal.CurrentScheduledAt.FormatMoscow()}</b> (МСК)",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to update vote message after rejection");
|
||||
}
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, decision.CallbackText, cancellationToken: ct);
|
||||
logger.LogInformation("Reschedule proposal {ProposalId} rejected by player {PlayerId}", command.ProposalId, playerId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (decision.ShouldRescheduleSession)
|
||||
{
|
||||
var newTime = new DateTimeOffset(proposal.ProposedAt, TimeSpan.Zero);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET scheduled_at = @NewTime,
|
||||
status = @Status,
|
||||
confirmation_message_id = NULL,
|
||||
link_message_id = NULL,
|
||||
updated_at = now()
|
||||
WHERE id = @SessionId
|
||||
""",
|
||||
new { NewTime = newTime, proposal.SessionId, Status = SessionStatus.Planned },
|
||||
transaction);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE reschedule_proposals SET status = 'Approved' WHERE id = @Id",
|
||||
new { Id = command.ProposalId },
|
||||
transaction);
|
||||
|
||||
if (decision.ShouldResetParticipantRsvps)
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE session_participants
|
||||
SET rsvp_status = 'Pending',
|
||||
responded_at = NULL
|
||||
WHERE session_id = @SessionId AND is_gm = false
|
||||
AND registration_status = @Active
|
||||
""",
|
||||
new { proposal.SessionId, Active = ParticipantRegistrationStatus.Active },
|
||||
transaction);
|
||||
}
|
||||
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: $"✅ <b>Перенос сессии «{System.Net.WebUtility.HtmlEncode(proposal.Title)}» одобрен!</b>\n\nВсе участники согласились.\n📅 Новое время: <b>{proposal.ProposedAt.FormatMoscow()}</b> (МСК)\n\n<i>Уведомления будут приходить согласно новому расписанию.</i>",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to update vote message after approval");
|
||||
}
|
||||
|
||||
await TryUpdateBatchMessage(proposal, ct);
|
||||
|
||||
logger.LogInformation(
|
||||
"Session {SessionId} rescheduled to {NewTime} (proposal {ProposalId})",
|
||||
proposal.SessionId,
|
||||
newTime,
|
||||
command.ProposalId);
|
||||
}
|
||||
else
|
||||
{
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
var voteText = HandleRescheduleTimeInputHandler.BuildVotingMessage(
|
||||
proposal.Title,
|
||||
proposal.CurrentScheduledAt,
|
||||
new DateTimeOffset(proposal.ProposedAt, TimeSpan.Zero),
|
||||
participants,
|
||||
approvedPlayerIds);
|
||||
|
||||
var keyboard = new InlineKeyboardMarkup([
|
||||
[
|
||||
InlineKeyboardButton.WithCallbackData("✅ Согласен", $"reschedule_vote:yes:{command.ProposalId}"),
|
||||
InlineKeyboardButton.WithCallbackData("❌ Против", $"reschedule_vote:no:{command.ProposalId}")
|
||||
]
|
||||
]);
|
||||
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: voteText,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: keyboard,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to update vote message with progress");
|
||||
}
|
||||
}
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, decision.CallbackText, cancellationToken: ct);
|
||||
}
|
||||
|
||||
private async Task TryUpdateBatchMessage(VoteProposalDto proposal, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
|
||||
var batchSessions = (await connection.QueryAsync<SessionBatchDto>(
|
||||
"SELECT id AS SessionId, scheduled_at AS ScheduledAt, status AS Status, max_players AS MaxPlayers FROM sessions WHERE batch_id = @BatchId ORDER BY scheduled_at",
|
||||
new { proposal.BatchId })).ToList();
|
||||
|
||||
var batchParticipants = (await connection.QueryAsync<ParticipantBatchDto>(
|
||||
"""
|
||||
SELECT sp.session_id AS SessionId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
sp.registration_status AS RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON sp.player_id = p.id
|
||||
JOIN sessions s ON sp.session_id = s.id
|
||||
WHERE s.batch_id = @BatchId AND sp.is_gm = false
|
||||
ORDER BY sp.registration_status ASC, sp.created_at ASC, sp.responded_at ASC, p.created_at ASC
|
||||
""",
|
||||
new { proposal.BatchId })).ToList();
|
||||
|
||||
if (proposal.BatchMessageId.HasValue)
|
||||
{
|
||||
var renderResult = SessionBatchRenderer.Render(proposal.Title, batchSessions, batchParticipants);
|
||||
|
||||
await bot.EditMessageText(
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageId: proposal.BatchMessageId.Value,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: proposal.TelegramChatId,
|
||||
text: $"📣 Расписание обновлено! Сессия «{proposal.Title}» перенесена на <b>{proposal.ProposedAt.FormatMoscow()}</b> (МСК).",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
await bot.EditMessageText(
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: voteText,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: keyboard,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to update batch message for proposal {ProposalId}", proposal.Id);
|
||||
logger.LogWarning(ex, "Failed to update reschedule vote message for proposal {ProposalId}", proposal.Id);
|
||||
}
|
||||
|
||||
await bot.AnswerCallbackQuery(
|
||||
command.CallbackQueryId,
|
||||
"Ваш голос учтён. До дедлайна его можно изменить.",
|
||||
cancellationToken: ct);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,14 @@ public sealed record InitiateRescheduleCommand(
|
||||
|
||||
// ── DTOs ─────────────────────────────────────────────────────────────
|
||||
|
||||
internal sealed record RescheduleSessionInfoDto(string Title, long GmId);
|
||||
internal sealed record RescheduleSessionInfoDto(string Title, bool CanManage);
|
||||
|
||||
// ── Handler ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Handles the "⏰ Перенести" button press from the batch message.
|
||||
/// Creates a reschedule proposal in AwaitingTime status and prompts
|
||||
/// the GM to enter the new time via a regular text message.
|
||||
/// the GM to enter 2-3 new time options and a voting deadline.
|
||||
/// </summary>
|
||||
public sealed class InitiateRescheduleHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
@@ -34,15 +34,21 @@ public sealed class InitiateRescheduleHandler(
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
|
||||
// 1. Verify GM ownership
|
||||
// 1. Verify group management access.
|
||||
var session = await connection.QuerySingleOrDefaultAsync<RescheduleSessionInfoDto>(
|
||||
"""
|
||||
SELECT s.title AS Title, g.gm_telegram_id AS GmId
|
||||
SELECT s.title AS Title,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = s.group_id
|
||||
AND p.telegram_id = @TelegramUserId
|
||||
) AS CanManage
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
WHERE s.id = @SessionId AND s.status != @Cancelled
|
||||
""",
|
||||
new { command.SessionId, Cancelled = SessionStatus.Cancelled });
|
||||
new { command.SessionId, command.TelegramUserId, Cancelled = SessionStatus.Cancelled });
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
@@ -50,10 +56,10 @@ public sealed class InitiateRescheduleHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.GmId != command.TelegramUserId)
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId,
|
||||
"Только Мастер Игры (GM) может переносить сессию.", showAlert: true, cancellationToken: ct);
|
||||
"Только owner или co-GM может переносить сессию.", showAlert: true, cancellationToken: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,11 +92,20 @@ public sealed class InitiateRescheduleHandler(
|
||||
|
||||
// 4. Prompt GM in chat
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId,
|
||||
"Введите новое время в чат (формат: ДД.ММ.ГГГГ ЧЧ:ММ)", cancellationToken: ct);
|
||||
"Введите 2-3 варианта времени и дедлайн голосования.", cancellationToken: ct);
|
||||
|
||||
await bot.SendMessage(
|
||||
chatId: command.ChatId,
|
||||
text: $"⏰ Укажите новое время для сессии «{session.Title}» в формате:\n<code>ДД.ММ.ГГГГ ЧЧ:ММ</code>\n\nНапример: <code>25.04.2026 19:30</code>",
|
||||
text: $"""
|
||||
⏰ Укажите 2-3 варианта времени для сессии «{session.Title}» и дедлайн голосования.
|
||||
|
||||
Формат:
|
||||
<code>25.04.2026 19:30
|
||||
26.04.2026 18:00
|
||||
Дедлайн: 25.04.2026 12:00</code>
|
||||
|
||||
Дедлайн должен быть в будущем и раньше первого предложенного времени.
|
||||
""",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
@@ -9,27 +9,57 @@ internal enum RescheduleVoteOutcome
|
||||
|
||||
internal sealed record RescheduleVoteDecision(
|
||||
RescheduleVoteOutcome Outcome,
|
||||
string CallbackText,
|
||||
bool ShouldRescheduleSession,
|
||||
bool ShouldResetParticipantRsvps);
|
||||
string Reason,
|
||||
Guid? SelectedOptionId = null,
|
||||
string CallbackText = "",
|
||||
bool ShouldRescheduleSession = false,
|
||||
bool ShouldResetParticipantRsvps = false);
|
||||
|
||||
internal static class RescheduleVoteRules
|
||||
{
|
||||
public static RescheduleVoteDecision SelectWinner(IReadOnlyList<RescheduleOptionVoteCount> voteCounts)
|
||||
{
|
||||
var maxVotes = voteCounts.Count == 0 ? 0 : voteCounts.Max(x => x.VoteCount);
|
||||
if (maxVotes == 0)
|
||||
{
|
||||
return new RescheduleVoteDecision(
|
||||
RescheduleVoteOutcome.Rejected,
|
||||
"Никто не проголосовал до дедлайна, перенос не применяется.");
|
||||
}
|
||||
|
||||
var winners = voteCounts.Where(x => x.VoteCount == maxVotes).ToList();
|
||||
if (winners.Count > 1)
|
||||
{
|
||||
return new RescheduleVoteDecision(
|
||||
RescheduleVoteOutcome.Rejected,
|
||||
"Голоса разделились поровну, перенос не применяется.");
|
||||
}
|
||||
|
||||
return new RescheduleVoteDecision(
|
||||
RescheduleVoteOutcome.Approved,
|
||||
"Победил вариант с большинством голосов.",
|
||||
winners[0].OptionId,
|
||||
ShouldRescheduleSession: true,
|
||||
ShouldResetParticipantRsvps: true);
|
||||
}
|
||||
|
||||
public static RescheduleVoteDecision Evaluate(string vote, int totalParticipants, int approvedParticipants)
|
||||
{
|
||||
if (string.Equals(vote, "no", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new RescheduleVoteDecision(
|
||||
Outcome: RescheduleVoteOutcome.Rejected,
|
||||
CallbackText: "\u0412\u044b \u043f\u0440\u043e\u0433\u043e\u043b\u043e\u0441\u043e\u0432\u0430\u043b\u0438 \u043f\u0440\u043e\u0442\u0438\u0432 \u043f\u0435\u0440\u0435\u043d\u043e\u0441\u0430.",
|
||||
ShouldRescheduleSession: false,
|
||||
ShouldResetParticipantRsvps: false);
|
||||
Reason: "\u041e\u0434\u0438\u043d \u0438\u0437 \u0443\u0447\u0430\u0441\u0442\u043d\u0438\u043a\u043e\u0432 \u043e\u0442\u043a\u043b\u043e\u043d\u0438\u043b \u043f\u0435\u0440\u0435\u043d\u043e\u0441.",
|
||||
CallbackText: "\u0412\u044b \u043f\u0440\u043e\u0433\u043e\u043b\u043e\u0441\u043e\u0432\u0430\u043b\u0438 \u043f\u0440\u043e\u0442\u0438\u0432 \u043f\u0435\u0440\u0435\u043d\u043e\u0441\u0430.");
|
||||
}
|
||||
|
||||
var everyoneApproved = approvedParticipants == totalParticipants;
|
||||
|
||||
return new RescheduleVoteDecision(
|
||||
Outcome: everyoneApproved ? RescheduleVoteOutcome.Approved : RescheduleVoteOutcome.Pending,
|
||||
Reason: everyoneApproved
|
||||
? "\u0412\u0441\u0435 \u0443\u0447\u0430\u0441\u0442\u043d\u0438\u043a\u0438 \u0441\u043e\u0433\u043b\u0430\u0441\u043d\u044b."
|
||||
: "\u0413\u043e\u043b\u043e\u0441\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0430\u0435\u0442\u0441\u044f.",
|
||||
CallbackText: everyoneApproved
|
||||
? "\u0412\u044b \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u043b\u0438 \u043f\u0435\u0440\u0435\u043d\u043e\u0441! \u0412\u0441\u0435 \u0441\u043e\u0433\u043b\u0430\u0441\u043d\u044b \u2014 \u0432\u0440\u0435\u043c\u044f \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u043e."
|
||||
: "\u0412\u044b \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u043b\u0438 \u043f\u0435\u0440\u0435\u043d\u043e\u0441!",
|
||||
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
|
||||
internal sealed record DueRescheduleProposalDto(
|
||||
Guid Id,
|
||||
Guid SessionId,
|
||||
DateTimeOffset VotingDeadlineAt,
|
||||
string Title,
|
||||
DateTime CurrentScheduledAt,
|
||||
Guid BatchId,
|
||||
int? BatchMessageId,
|
||||
int? VoteMessageId,
|
||||
long TelegramChatId,
|
||||
string NotificationMode);
|
||||
|
||||
public sealed class RescheduleVotingDeadlineService(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<RescheduleVotingDeadlineService> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ProcessDueProposals(stoppingToken);
|
||||
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
await ProcessDueProposals(stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ProcessDueProposals(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
var proposalIds = (await connection.QueryAsync<Guid>(
|
||||
"""
|
||||
SELECT id
|
||||
FROM reschedule_proposals
|
||||
WHERE status = 'Voting'
|
||||
AND voting_deadline_at IS NOT NULL
|
||||
AND voting_deadline_at <= now()
|
||||
ORDER BY voting_deadline_at
|
||||
LIMIT 25
|
||||
""")).ToList();
|
||||
|
||||
foreach (var proposalId in proposalIds)
|
||||
{
|
||||
await FinalizeProposal(proposalId, ct);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to process due reschedule voting proposals");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FinalizeProposal(Guid proposalId, CancellationToken ct)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
await using var transaction = await connection.BeginTransactionAsync(ct);
|
||||
|
||||
var proposal = await connection.QuerySingleOrDefaultAsync<DueRescheduleProposalDto>(
|
||||
"""
|
||||
SELECT rp.id AS Id,
|
||||
rp.session_id AS SessionId,
|
||||
rp.voting_deadline_at AS VotingDeadlineAt,
|
||||
rp.vote_message_id AS VoteMessageId,
|
||||
s.title AS Title,
|
||||
s.scheduled_at AS CurrentScheduledAt,
|
||||
s.batch_id AS BatchId,
|
||||
s.batch_message_id AS BatchMessageId,
|
||||
s.notification_mode AS NotificationMode,
|
||||
g.telegram_chat_id AS TelegramChatId
|
||||
FROM reschedule_proposals rp
|
||||
JOIN sessions s ON s.id = rp.session_id
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE rp.id = @ProposalId
|
||||
AND rp.status = 'Voting'
|
||||
AND rp.voting_deadline_at IS NOT NULL
|
||||
AND rp.voting_deadline_at <= now()
|
||||
FOR UPDATE
|
||||
""",
|
||||
new { ProposalId = proposalId },
|
||||
transaction);
|
||||
|
||||
if (proposal is null)
|
||||
return;
|
||||
|
||||
var participants = (await connection.QueryAsync<VoteParticipantDto>(
|
||||
"""
|
||||
SELECT p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
p.telegram_id AS TelegramId
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
ORDER BY p.display_name
|
||||
""",
|
||||
new { proposal.SessionId, Active = ParticipantRegistrationStatus.Active },
|
||||
transaction)).ToList();
|
||||
|
||||
var options = (await connection.QueryAsync<RescheduleOptionDto>(
|
||||
"""
|
||||
SELECT id AS OptionId,
|
||||
display_order AS DisplayOrder,
|
||||
proposed_at AS ProposedAt
|
||||
FROM reschedule_options
|
||||
WHERE proposal_id = @ProposalId
|
||||
ORDER BY display_order
|
||||
""",
|
||||
new { ProposalId = proposal.Id },
|
||||
transaction)).ToList();
|
||||
|
||||
var votes = (await connection.QueryAsync<RescheduleOptionVoteDto>(
|
||||
"""
|
||||
SELECT rov.option_id AS OptionId,
|
||||
p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername
|
||||
FROM reschedule_option_votes rov
|
||||
JOIN players p ON p.id = rov.player_id
|
||||
WHERE rov.proposal_id = @ProposalId
|
||||
ORDER BY rov.voted_at, p.display_name
|
||||
""",
|
||||
new { ProposalId = proposal.Id },
|
||||
transaction)).ToList();
|
||||
|
||||
var voteCounts = options
|
||||
.Select(option => new RescheduleOptionVoteCount(
|
||||
option.OptionId,
|
||||
votes.Count(vote => vote.OptionId == option.OptionId)))
|
||||
.ToList();
|
||||
var decision = RescheduleVoteRules.SelectWinner(voteCounts);
|
||||
var selectedOption = decision.SelectedOptionId is { } selectedOptionId
|
||||
? options.Single(x => x.OptionId == selectedOptionId)
|
||||
: null;
|
||||
|
||||
if (selectedOption is not null)
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET scheduled_at = @NewTime,
|
||||
status = @Status,
|
||||
confirmation_message_id = NULL,
|
||||
link_message_id = NULL,
|
||||
one_hour_reminder_processed_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE id = @SessionId
|
||||
""",
|
||||
new { NewTime = selectedOption.ProposedAt, proposal.SessionId, Status = SessionStatus.Planned },
|
||||
transaction);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE session_participants
|
||||
SET rsvp_status = 'Pending',
|
||||
responded_at = NULL
|
||||
WHERE session_id = @SessionId
|
||||
AND is_gm = false
|
||||
AND registration_status = @Active
|
||||
""",
|
||||
new { proposal.SessionId, Active = ParticipantRegistrationStatus.Active },
|
||||
transaction);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE reschedule_proposals
|
||||
SET status = 'Approved',
|
||||
selected_option_id = @SelectedOptionId,
|
||||
proposed_at = @ProposedAt
|
||||
WHERE id = @ProposalId
|
||||
""",
|
||||
new
|
||||
{
|
||||
ProposalId = proposal.Id,
|
||||
SelectedOptionId = selectedOption.OptionId,
|
||||
ProposedAt = selectedOption.ProposedAt
|
||||
},
|
||||
transaction);
|
||||
}
|
||||
else
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE reschedule_proposals SET status = 'Rejected' WHERE id = @ProposalId",
|
||||
new { ProposalId = proposal.Id },
|
||||
transaction);
|
||||
}
|
||||
|
||||
var directRecipients = participants
|
||||
.Select(p => new DirectNotificationRecipient(p.TelegramId, p.DisplayName))
|
||||
.ToList();
|
||||
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
await TryUpdateVoteMessage(proposal, options, participants, votes, decision, selectedOption, ct);
|
||||
|
||||
if (selectedOption is not null)
|
||||
{
|
||||
await TryUpdateBatchMessage(proposal, ct);
|
||||
}
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(proposal.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
await SendDirectResult(proposal, directRecipients, decision, selectedOption, ct);
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Finalized reschedule proposal {ProposalId} for session {SessionId} with outcome {Outcome}",
|
||||
proposal.Id,
|
||||
proposal.SessionId,
|
||||
decision.Outcome);
|
||||
}
|
||||
|
||||
private async Task TryUpdateVoteMessage(
|
||||
DueRescheduleProposalDto proposal,
|
||||
IReadOnlyList<RescheduleOptionDto> options,
|
||||
IReadOnlyList<VoteParticipantDto> participants,
|
||||
IReadOnlyList<RescheduleOptionVoteDto> votes,
|
||||
RescheduleVoteDecision decision,
|
||||
RescheduleOptionDto? selectedOption,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (proposal.VoteMessageId is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var resultText = selectedOption is not null
|
||||
? $"✅ <b>Голосование завершено.</b>\nПобедил вариант {selectedOption.DisplayOrder}: <b>{selectedOption.ProposedAt.FormatMoscow()}</b> (МСК)."
|
||||
: $"❌ <b>Голосование завершено.</b>\n{System.Net.WebUtility.HtmlEncode(decision.Reason)}";
|
||||
|
||||
var text = $"""
|
||||
{HandleRescheduleTimeInputHandler.BuildVotingMessage(
|
||||
proposal.Title,
|
||||
proposal.CurrentScheduledAt,
|
||||
proposal.VotingDeadlineAt,
|
||||
options,
|
||||
participants,
|
||||
votes)}
|
||||
|
||||
{resultText}
|
||||
""";
|
||||
|
||||
await bot.EditMessageText(
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageId: proposal.VoteMessageId.Value,
|
||||
text: text,
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to update finalized reschedule vote message for proposal {ProposalId}", proposal.Id);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryUpdateBatchMessage(DueRescheduleProposalDto proposal, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
|
||||
var batchSessions = (await connection.QueryAsync<SessionBatchDto>(
|
||||
"SELECT id AS SessionId, scheduled_at AS ScheduledAt, status AS Status, max_players AS MaxPlayers FROM sessions WHERE batch_id = @BatchId ORDER BY scheduled_at",
|
||||
new { proposal.BatchId })).ToList();
|
||||
|
||||
var batchParticipants = (await connection.QueryAsync<ParticipantBatchDto>(
|
||||
"""
|
||||
SELECT sp.session_id AS SessionId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
sp.registration_status AS RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON sp.player_id = p.id
|
||||
JOIN sessions s ON sp.session_id = s.id
|
||||
WHERE s.batch_id = @BatchId AND sp.is_gm = false
|
||||
ORDER BY sp.registration_status ASC, sp.created_at ASC, sp.responded_at ASC, p.created_at ASC
|
||||
""",
|
||||
new { proposal.BatchId })).ToList();
|
||||
|
||||
if (proposal.BatchMessageId.HasValue)
|
||||
{
|
||||
var view = SessionBatchViewBuilder.Build(proposal.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageId: proposal.BatchMessageId.Value,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: proposal.TelegramChatId,
|
||||
text: $"📣 Расписание обновлено после голосования за перенос сессии «{System.Net.WebUtility.HtmlEncode(proposal.Title)}».",
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to update batch message for finalized proposal {ProposalId}", proposal.Id);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendDirectResult(
|
||||
DueRescheduleProposalDto proposal,
|
||||
IReadOnlyList<DirectNotificationRecipient> recipients,
|
||||
RescheduleVoteDecision decision,
|
||||
RescheduleOptionDto? selectedOption,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var htmlText = selectedOption is not null
|
||||
? $"""
|
||||
✅ <b>Сессия перенесена по итогам голосования</b>
|
||||
|
||||
📌 <b>{System.Net.WebUtility.HtmlEncode(proposal.Title)}</b>
|
||||
📅 Новое время: <b>{selectedOption.ProposedAt.FormatMoscow()}</b> (МСК)
|
||||
"""
|
||||
: $"""
|
||||
❌ <b>Перенос сессии отклонён по итогам голосования</b>
|
||||
|
||||
📌 <b>{System.Net.WebUtility.HtmlEncode(proposal.Title)}</b>
|
||||
📅 Время остаётся прежним: <b>{proposal.CurrentScheduledAt.FormatMoscow()}</b> (МСК)
|
||||
Причина: {System.Net.WebUtility.HtmlEncode(decision.Reason)}
|
||||
""";
|
||||
|
||||
await directSender.SendAsync(
|
||||
recipients,
|
||||
htmlText,
|
||||
selectedOption is not null ? "reschedule-vote-approved" : "reschedule-vote-rejected",
|
||||
proposal.SessionId,
|
||||
ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
|
||||
internal sealed record RescheduleVotingInput(
|
||||
IReadOnlyList<DateTimeOffset> Options,
|
||||
DateTimeOffset Deadline)
|
||||
{
|
||||
private static readonly Regex DateTimePattern = new(
|
||||
@"(?<date>\d{1,2}\.\d{2}\.\d{4})\s+(?<time>\d{1,2}:\d{2})",
|
||||
RegexOptions.CultureInvariant);
|
||||
|
||||
public static bool TryParse(
|
||||
string text,
|
||||
DateTimeOffset nowUtc,
|
||||
out RescheduleVotingInput input,
|
||||
out string error)
|
||||
{
|
||||
input = new RescheduleVotingInput([], default);
|
||||
error = string.Empty;
|
||||
|
||||
var options = new List<DateTimeOffset>();
|
||||
DateTimeOffset? deadline = null;
|
||||
|
||||
foreach (var rawLine in text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
var line = rawLine.Trim();
|
||||
var match = DateTimePattern.Match(line);
|
||||
if (!match.Success)
|
||||
continue;
|
||||
|
||||
var value = $"{match.Groups["date"].Value} {match.Groups["time"].Value}";
|
||||
if (!MoscowTime.TryParseMoscow(value, out var parsed))
|
||||
continue;
|
||||
|
||||
if (IsDeadlineLine(line))
|
||||
{
|
||||
deadline = parsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
options.Add(parsed);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.Count is < 2 or > 3)
|
||||
{
|
||||
error = "Укажите от 2 до 3 вариантов времени.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.Distinct().Count() != options.Count)
|
||||
{
|
||||
error = "Варианты времени не должны повторяться.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (deadline is null)
|
||||
{
|
||||
error = "Укажите дедлайн голосования строкой «Дедлайн: ДД.ММ.ГГГГ ЧЧ:ММ».";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.Any(option => option <= nowUtc))
|
||||
{
|
||||
error = "Все варианты времени должны быть в будущем.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (deadline.Value <= nowUtc)
|
||||
{
|
||||
error = "Дедлайн голосования должен быть в будущем.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (deadline.Value >= options.Min())
|
||||
{
|
||||
error = "Дедлайн голосования должен быть раньше первого предложенного времени.";
|
||||
return false;
|
||||
}
|
||||
|
||||
input = new RescheduleVotingInput(options, deadline.Value);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsDeadlineLine(string line)
|
||||
{
|
||||
var normalized = line.TrimStart('-', '*', ' ', '\t').ToLowerInvariant();
|
||||
|
||||
return normalized.StartsWith("дедлайн", StringComparison.Ordinal)
|
||||
|| normalized.StartsWith("deadline", StringComparison.Ordinal)
|
||||
|| normalized.StartsWith("до:", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record RescheduleOptionDto(
|
||||
Guid OptionId,
|
||||
int DisplayOrder,
|
||||
DateTimeOffset ProposedAt);
|
||||
|
||||
internal sealed record RescheduleOptionVoteDto(
|
||||
Guid OptionId,
|
||||
Guid PlayerId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername);
|
||||
|
||||
internal sealed record RescheduleOptionVoteCount(
|
||||
Guid OptionId,
|
||||
int VoteCount);
|
||||
@@ -2,6 +2,7 @@ using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Bot.Features.Confirmation.SendConfirmation;
|
||||
using GmRelay.Bot.Features.Reminders.SendJoinLink;
|
||||
using GmRelay.Bot.Features.Reminders.SendOneHourReminder;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Scheduling;
|
||||
@@ -17,11 +18,13 @@ namespace GmRelay.Bot.Infrastructure.Scheduling;
|
||||
public sealed class SessionSchedulerService(
|
||||
NpgsqlDataSource dataSource,
|
||||
SendConfirmationHandler confirmationHandler,
|
||||
SendOneHourReminderHandler oneHourReminderHandler,
|
||||
SendJoinLinkHandler joinLinkHandler,
|
||||
ILogger<SessionSchedulerService> logger) : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan TickInterval = TimeSpan.FromMinutes(1);
|
||||
private static readonly TimeSpan ConfirmationLeadTime = TimeSpan.FromHours(24);
|
||||
private static readonly TimeSpan OneHourReminderLeadTime = TimeSpan.FromHours(1);
|
||||
private static readonly TimeSpan JoinLinkLeadTime = TimeSpan.FromMinutes(5);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
@@ -36,6 +39,7 @@ public sealed class SessionSchedulerService(
|
||||
try
|
||||
{
|
||||
await ProcessConfirmationTriggers(stoppingToken);
|
||||
await ProcessOneHourReminderTriggers(stoppingToken);
|
||||
await ProcessJoinLinkTriggers(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
@@ -52,6 +56,42 @@ public sealed class SessionSchedulerService(
|
||||
logger.LogInformation("Session scheduler stopped");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// T-1h trigger: process direct reminders according to the session notification mode.
|
||||
/// </summary>
|
||||
private async Task ProcessOneHourReminderTriggers(CancellationToken ct)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
|
||||
var sessionIds = await connection.QueryAsync<Guid>(
|
||||
"""
|
||||
SELECT id
|
||||
FROM sessions
|
||||
WHERE status IN (@Confirmed, @ConfirmationSent)
|
||||
AND scheduled_at - @LeadTime <= now()
|
||||
AND one_hour_reminder_processed_at IS NULL
|
||||
""",
|
||||
new
|
||||
{
|
||||
Confirmed = SessionStatus.Confirmed,
|
||||
ConfirmationSent = SessionStatus.ConfirmationSent,
|
||||
LeadTime = OneHourReminderLeadTime
|
||||
});
|
||||
|
||||
foreach (var sessionId in sessionIds)
|
||||
{
|
||||
try
|
||||
{
|
||||
await oneHourReminderHandler.HandleAsync(sessionId, ct);
|
||||
logger.LogInformation("One-hour reminder processed for session {SessionId}", sessionId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to process one-hour reminder for session {SessionId}", sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// T-24h trigger: find sessions that need confirmation requests sent.
|
||||
/// Condition: status='Planned' AND scheduled_at minus 24h is in the past.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
/// <summary>
|
||||
/// Handles editing batch messages that may be either text or photo messages.
|
||||
/// When the batch was created with SendPhoto (image + caption), we need
|
||||
/// EditMessageCaption instead of EditMessageText.
|
||||
/// </summary>
|
||||
public static class BatchMessageEditor
|
||||
{
|
||||
/// <summary>
|
||||
/// Edits a batch message, automatically detecting whether it is a text or photo message.
|
||||
/// Tries EditMessageText first; on failure falls back to EditMessageCaption.
|
||||
/// </summary>
|
||||
public static async Task EditBatchMessageAsync(
|
||||
ITelegramBotClient bot,
|
||||
long chatId,
|
||||
int messageId,
|
||||
string text,
|
||||
InlineKeyboardMarkup? replyMarkup,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
text: text,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: replyMarkup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (global::Telegram.Bot.Exceptions.ApiRequestException ex)
|
||||
when (ex.Message.Contains("there is no text in the message", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// The batch message is a photo — use EditMessageCaption instead.
|
||||
// Caption is limited to 1024 chars; if text exceeds that, truncate gracefully.
|
||||
var caption = text.Length <= 1024 ? text : text[..1021] + "...";
|
||||
await bot.EditMessageCaption(
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
caption: caption,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: replyMarkup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
public sealed class TelegramMiniAppMenuButtonService(
|
||||
ITelegramBotClient bot,
|
||||
IConfiguration configuration,
|
||||
ILogger<TelegramMiniAppMenuButtonService> logger) : IHostedService
|
||||
{
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var miniAppUrl = configuration["Telegram:MiniAppUrl"];
|
||||
if (string.IsNullOrWhiteSpace(miniAppUrl))
|
||||
{
|
||||
logger.LogInformation("Telegram Mini App URL is not configured; menu button setup skipped.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(miniAppUrl, UriKind.Absolute, out var uri) ||
|
||||
(uri.Scheme != Uri.UriSchemeHttps && !uri.IsLoopback))
|
||||
{
|
||||
logger.LogWarning("Telegram Mini App URL {MiniAppUrl} is not a valid HTTPS URL.", miniAppUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await bot.SetChatMenuButton(
|
||||
menuButton: new MenuButtonWebApp
|
||||
{
|
||||
Text = "Dashboard",
|
||||
WebApp = new WebAppInfo(miniAppUrl)
|
||||
},
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
logger.LogInformation("Telegram Mini App menu button configured for {MiniAppUrl}.", miniAppUrl);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to configure Telegram Mini App menu button.");
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// NOTE: duplicated in GmRelay.Web/Services/TelegramSessionBatchRenderer.cs
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
public static class TelegramSessionBatchRenderer
|
||||
{
|
||||
public static (string Text, InlineKeyboardMarkup Markup) Render(SessionBatchViewModel view)
|
||||
{
|
||||
var messageText = $"🎲 <b>Новые игры:</b> {System.Net.WebUtility.HtmlEncode(view.Title)}\n\n" +
|
||||
$"<b>Расписание:</b>\n\n";
|
||||
|
||||
var buttons = new List<InlineKeyboardButton[]>();
|
||||
|
||||
foreach (var session in view.Sessions)
|
||||
{
|
||||
messageText += $"📅 <b>{session.ScheduledAt.FormatMoscow()}</b>\n";
|
||||
messageText += session.MaxPlayers.HasValue
|
||||
? $"👥 Места: {session.ActivePlayerCount}/{session.MaxPlayers.Value}\n"
|
||||
: $"👥 Игроки ({session.ActivePlayerCount}):\n";
|
||||
|
||||
if (session.ActivePlayers.Count > 0)
|
||||
{
|
||||
messageText += string.Join("\n", session.ActivePlayers.Select(p =>
|
||||
$" 👤 {(p.TelegramUsername != null ? "@" + p.TelegramUsername : p.DisplayName)}")) + "\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
messageText += " <i>Пока никто не записался</i>\n";
|
||||
}
|
||||
|
||||
if (session.WaitlistedPlayers.Count > 0)
|
||||
{
|
||||
messageText += $"⏳ Лист ожидания ({session.WaitlistedPlayers.Count}):\n";
|
||||
messageText += string.Join("\n", session.WaitlistedPlayers.Select(p =>
|
||||
$" ⏱ {(p.TelegramUsername != null ? "@" + p.TelegramUsername : p.DisplayName)}")) + "\n";
|
||||
}
|
||||
|
||||
if (GmRelay.Shared.Domain.SessionStatus.IsCancelled(session.Status))
|
||||
{
|
||||
messageText += "❌ <i>Сессия отменена</i>\n\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
messageText += "\n";
|
||||
var actionRow = session.AvailableActions
|
||||
.Select(a => InlineKeyboardButton.WithCallbackData(a.Label, $"{a.ActionKey}:{a.SessionId}"))
|
||||
.ToArray();
|
||||
if (actionRow.Length > 0)
|
||||
buttons.Add(actionRow);
|
||||
}
|
||||
}
|
||||
|
||||
return (messageText, new InlineKeyboardMarkup(buttons));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ using GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
@@ -30,6 +31,7 @@ public sealed class UpdateRouter(
|
||||
HandleRescheduleTimeInputHandler rescheduleTimeInputHandler,
|
||||
HandleRescheduleVoteHandler rescheduleVoteHandler,
|
||||
ITelegramBotClient bot,
|
||||
IConfiguration configuration,
|
||||
ILogger<UpdateRouter> logger) : ITelegramUpdateHandler
|
||||
{
|
||||
public async Task RouteAsync(Update update, CancellationToken ct)
|
||||
@@ -40,17 +42,26 @@ public sealed class UpdateRouter(
|
||||
await HandleCallbackQueryAsync(query, ct);
|
||||
break;
|
||||
|
||||
case { Message: { Text: { } text } message } when text.StartsWith('/'):
|
||||
await HandleCommandAsync(message, text, ct);
|
||||
break;
|
||||
case { Message: { } message }:
|
||||
var commandText = GetCommandText(message);
|
||||
if (commandText.StartsWith("/", StringComparison.Ordinal))
|
||||
{
|
||||
await HandleCommandAsync(message, commandText, ct);
|
||||
break;
|
||||
}
|
||||
|
||||
if (message.Text is not null)
|
||||
{
|
||||
await rescheduleTimeInputHandler.TryHandleAsync(message, ct);
|
||||
}
|
||||
|
||||
// Non-command text messages — check for reschedule time input
|
||||
case { Message: { Text: { } } message } when !message.Text!.StartsWith('/'):
|
||||
await rescheduleTimeInputHandler.TryHandleAsync(message, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string GetCommandText(Message message)
|
||||
=> (message.Text ?? message.Caption ?? string.Empty).TrimStart();
|
||||
|
||||
private async Task HandleCallbackQueryAsync(CallbackQuery query, CancellationToken ct)
|
||||
{
|
||||
if (query.Data is not { } data || query.Message is not { } message)
|
||||
@@ -139,15 +150,10 @@ public sealed class UpdateRouter(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action == "reschedule_vote" && parts.Length >= 3 && Guid.TryParse(parts[2], out var proposalId))
|
||||
if (action == "reschedule_vote" && parts.Length >= 2 && Guid.TryParse(parts[1], out var optionId))
|
||||
{
|
||||
var vote = parts[1]; // "yes" or "no"
|
||||
if (vote is not ("yes" or "no"))
|
||||
return;
|
||||
|
||||
var command = new HandleRescheduleVoteCommand(
|
||||
ProposalId: proposalId,
|
||||
Vote: vote,
|
||||
OptionId: optionId,
|
||||
TelegramUserId: query.From.Id,
|
||||
CallbackQueryId: query.Id,
|
||||
ChatId: message.Chat.Id,
|
||||
@@ -193,10 +199,7 @@ public sealed class UpdateRouter(
|
||||
switch (command)
|
||||
{
|
||||
case "/start":
|
||||
await bot.SendMessage(
|
||||
chatId: message.Chat.Id,
|
||||
text: "GM-Relay Bot ready. Use /help for commands.",
|
||||
cancellationToken: ct);
|
||||
await SendStartMessageAsync(message, ct);
|
||||
break;
|
||||
|
||||
case "/newsession":
|
||||
@@ -222,8 +225,14 @@ public sealed class UpdateRouter(
|
||||
Время: 15.05.2026 19:30
|
||||
Мест: 4
|
||||
Ссылка: https://link
|
||||
Картинка: https://cover
|
||||
|
||||
Для регулярного расписания можно указать одну дату:
|
||||
Игр: 4
|
||||
Интервал: 7
|
||||
|
||||
/listsessions — список предстоящих сессий
|
||||
Для owner/co-GM /listsessions показывает кнопки отмены, переноса, удаления и повышения из листа ожидания.
|
||||
Игроки могут записаться кнопкой «На дату» и сняться кнопкой «Выйти».
|
||||
/help — эта справка
|
||||
""",
|
||||
@@ -236,4 +245,24 @@ public sealed class UpdateRouter(
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendStartMessageAsync(Message message, CancellationToken ct)
|
||||
{
|
||||
var miniAppUrl = configuration["Telegram:MiniAppUrl"];
|
||||
if (string.IsNullOrWhiteSpace(miniAppUrl))
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: message.Chat.Id,
|
||||
text: "GM-Relay Bot ready. Use /help for commands.",
|
||||
cancellationToken: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await bot.SendMessage(
|
||||
chatId: message.Chat.Id,
|
||||
text: "GM-Relay Bot ready. Откройте dashboard внутри Telegram или используйте /help для команд.",
|
||||
replyMarkup: new InlineKeyboardMarkup(
|
||||
InlineKeyboardButton.WithWebApp("Открыть dashboard", new WebAppInfo(miniAppUrl))),
|
||||
cancellationToken: ct);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE sessions
|
||||
ADD COLUMN notification_mode VARCHAR(50) NOT NULL DEFAULT 'GroupAndDirect'
|
||||
CHECK (notification_mode IN ('GroupAndDirect', 'GroupOnly')),
|
||||
ADD COLUMN one_hour_reminder_processed_at TIMESTAMPTZ;
|
||||
|
||||
CREATE INDEX ix_sessions_one_hour_reminders ON sessions (scheduled_at)
|
||||
WHERE status IN ('Confirmed', 'ConfirmationSent')
|
||||
AND one_hour_reminder_processed_at IS NULL;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Add explicit owner/co-GM management roles for each Telegram group.
|
||||
|
||||
INSERT INTO players (telegram_id, display_name)
|
||||
SELECT DISTINCT gg.gm_telegram_id,
|
||||
'GM ' || gg.gm_telegram_id::text
|
||||
FROM game_groups gg
|
||||
ON CONFLICT (telegram_id) DO NOTHING;
|
||||
|
||||
CREATE TABLE group_managers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
group_id UUID NOT NULL REFERENCES game_groups(id) ON DELETE CASCADE,
|
||||
player_id UUID NOT NULL REFERENCES players(id) ON DELETE CASCADE,
|
||||
role VARCHAR(50) NOT NULL CHECK (role IN ('Owner', 'CoGm')),
|
||||
added_by_player_id UUID REFERENCES players(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (group_id, player_id)
|
||||
);
|
||||
|
||||
INSERT INTO group_managers (group_id, player_id, role)
|
||||
SELECT gg.id, p.id, 'Owner'
|
||||
FROM game_groups gg
|
||||
JOIN players p ON p.telegram_id = gg.gm_telegram_id
|
||||
ON CONFLICT (group_id, player_id) DO NOTHING;
|
||||
|
||||
CREATE INDEX ix_group_managers_group_role ON group_managers (group_id, role);
|
||||
CREATE INDEX ix_group_managers_player ON group_managers (player_id);
|
||||
@@ -0,0 +1,35 @@
|
||||
-- Multi-option reschedule voting with a deadline.
|
||||
|
||||
ALTER TABLE reschedule_proposals
|
||||
ADD COLUMN voting_deadline_at TIMESTAMPTZ,
|
||||
ADD COLUMN selected_option_id UUID;
|
||||
|
||||
CREATE TABLE reschedule_options (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
proposal_id UUID NOT NULL REFERENCES reschedule_proposals(id) ON DELETE CASCADE,
|
||||
proposed_at TIMESTAMPTZ NOT NULL,
|
||||
display_order INTEGER NOT NULL CHECK (display_order BETWEEN 1 AND 3),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (proposal_id, id),
|
||||
UNIQUE (proposal_id, display_order),
|
||||
UNIQUE (proposal_id, proposed_at)
|
||||
);
|
||||
|
||||
CREATE TABLE reschedule_option_votes (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
proposal_id UUID NOT NULL REFERENCES reschedule_proposals(id) ON DELETE CASCADE,
|
||||
player_id UUID NOT NULL REFERENCES players(id) ON DELETE CASCADE,
|
||||
option_id UUID NOT NULL,
|
||||
voted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (proposal_id, player_id),
|
||||
FOREIGN KEY (proposal_id, option_id)
|
||||
REFERENCES reschedule_options(proposal_id, id)
|
||||
ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX ix_reschedule_voting_deadline
|
||||
ON reschedule_proposals (voting_deadline_at)
|
||||
WHERE status = 'Voting';
|
||||
|
||||
CREATE INDEX ix_reschedule_option_votes_option
|
||||
ON reschedule_option_votes (option_id);
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE campaign_templates (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
group_id UUID NOT NULL REFERENCES game_groups(id) ON DELETE CASCADE,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
title VARCHAR(500) NOT NULL,
|
||||
join_link TEXT NOT NULL,
|
||||
session_count INTEGER NOT NULL CHECK (session_count BETWEEN 1 AND 52),
|
||||
interval_days INTEGER NOT NULL CHECK (interval_days BETWEEN 1 AND 365),
|
||||
max_players INTEGER CHECK (max_players IS NULL OR max_players > 0),
|
||||
notification_mode VARCHAR(32) NOT NULL DEFAULT 'GroupAndDirect'
|
||||
CHECK (notification_mode IN ('GroupAndDirect', 'GroupOnly')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (group_id, name)
|
||||
);
|
||||
|
||||
CREATE INDEX ix_campaign_templates_group ON campaign_templates (group_id, created_at DESC);
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE calendar_subscriptions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
user_telegram_id BIGINT NOT NULL,
|
||||
group_id UUID REFERENCES game_groups(id) ON DELETE CASCADE,
|
||||
filter_type SMALLINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX ix_calendar_subscriptions_user_telegram_id ON calendar_subscriptions (user_telegram_id);
|
||||
@@ -0,0 +1,66 @@
|
||||
-- =============================================================
|
||||
-- Attendance statistics view for GM analytics
|
||||
-- Returns per-player aggregated metrics for a given game group.
|
||||
-- NOTE: waitlist count reflects CURRENT registration_status only.
|
||||
-- Full historical waitlist tracking will come with #15.
|
||||
-- =============================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_group_attendance_stats(p_group_id UUID)
|
||||
RETURNS TABLE (
|
||||
player_id UUID,
|
||||
display_name VARCHAR,
|
||||
telegram_username VARCHAR,
|
||||
total_sessions BIGINT,
|
||||
confirmed_count BIGINT,
|
||||
declined_count BIGINT,
|
||||
no_response_count BIGINT,
|
||||
waitlisted_count BIGINT,
|
||||
cancellation_affected_count BIGINT,
|
||||
attendance_rate NUMERIC
|
||||
) AS $$
|
||||
BEGIN
|
||||
RETURN QUERY
|
||||
WITH player_sessions AS (
|
||||
SELECT
|
||||
sp.player_id,
|
||||
s.id AS session_id,
|
||||
sp.rsvp_status,
|
||||
sp.registration_status,
|
||||
s.status AS session_status,
|
||||
s.scheduled_at
|
||||
FROM session_participants sp
|
||||
JOIN sessions s ON s.id = sp.session_id
|
||||
WHERE s.group_id = p_group_id
|
||||
),
|
||||
player_totals AS (
|
||||
SELECT
|
||||
ps.player_id,
|
||||
COUNT(*) FILTER (WHERE ps.session_status <> 'Cancelled') AS total_sessions,
|
||||
COUNT(*) FILTER (WHERE ps.rsvp_status = 'Confirmed' AND ps.session_status <> 'Cancelled') AS confirmed_count,
|
||||
COUNT(*) FILTER (WHERE ps.rsvp_status = 'Declined' AND ps.session_status <> 'Cancelled') AS declined_count,
|
||||
COUNT(*) FILTER (WHERE ps.rsvp_status = 'Pending' AND ps.scheduled_at < NOW() AND ps.session_status <> 'Cancelled') AS no_response_count,
|
||||
COUNT(*) FILTER (WHERE ps.registration_status = 'Waitlisted' AND ps.session_status <> 'Cancelled') AS waitlisted_count,
|
||||
COUNT(*) FILTER (WHERE ps.session_status = 'Cancelled') AS cancellation_affected_count
|
||||
FROM player_sessions ps
|
||||
GROUP BY ps.player_id
|
||||
)
|
||||
SELECT
|
||||
pt.player_id,
|
||||
p.display_name,
|
||||
p.telegram_username,
|
||||
pt.total_sessions,
|
||||
pt.confirmed_count,
|
||||
pt.declined_count,
|
||||
pt.no_response_count,
|
||||
pt.waitlisted_count,
|
||||
pt.cancellation_affected_count,
|
||||
ROUND(
|
||||
100.0 * pt.confirmed_count
|
||||
/ NULLIF(pt.total_sessions, 0),
|
||||
1
|
||||
) AS attendance_rate
|
||||
FROM player_totals pt
|
||||
JOIN players p ON p.id = pt.player_id
|
||||
ORDER BY pt.confirmed_count DESC, pt.total_sessions DESC;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql STABLE;
|
||||
@@ -0,0 +1,16 @@
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
CREATE TABLE session_audit_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
actor_telegram_id BIGINT NOT NULL,
|
||||
actor_name VARCHAR(255) NOT NULL,
|
||||
change_type VARCHAR(50) NOT NULL
|
||||
CHECK (change_type IN ('Title','Time','Link','MaxPlayers','Status','WaitlistPromote','PlayerRemoved','BatchRescheduled','Cancelled')),
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX ix_session_audit_log_session_id ON session_audit_log(session_id);
|
||||
CREATE INDEX ix_session_audit_log_changed_at ON session_audit_log(changed_at);
|
||||
@@ -1,6 +1,8 @@
|
||||
using GmRelay.Bot.Features.Confirmation.HandleRsvp;
|
||||
using GmRelay.Bot.Features.Confirmation.SendConfirmation;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Bot.Features.Reminders.SendJoinLink;
|
||||
using GmRelay.Bot.Features.Reminders.SendOneHourReminder;
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
using GmRelay.Bot.Infrastructure.Database;
|
||||
@@ -50,8 +52,10 @@ builder.Services.AddSingleton<ITelegramUpdateSource, TelegramUpdateSource>();
|
||||
|
||||
// ── Feature handlers (explicit registration — AOT safe) ──────────────
|
||||
builder.Services.AddSingleton<SendConfirmationHandler>();
|
||||
builder.Services.AddSingleton<DirectSessionNotificationSender>();
|
||||
builder.Services.AddSingleton<HandleRsvpHandler>();
|
||||
builder.Services.AddSingleton<SendJoinLinkHandler>();
|
||||
builder.Services.AddSingleton<SendOneHourReminderHandler>();
|
||||
builder.Services.AddSingleton<CreateSessionHandler>();
|
||||
builder.Services.AddSingleton<JoinSessionHandler>();
|
||||
builder.Services.AddSingleton<LeaveSessionHandler>();
|
||||
@@ -67,10 +71,12 @@ builder.Services.AddSingleton<HandleRescheduleVoteHandler>();
|
||||
// ── Telegram infrastructure ──────────────────────────────────────────
|
||||
builder.Services.AddSingleton<UpdateRouter>();
|
||||
builder.Services.AddSingleton<ITelegramUpdateHandler>(sp => sp.GetRequiredService<UpdateRouter>());
|
||||
builder.Services.AddHostedService<TelegramMiniAppMenuButtonService>();
|
||||
builder.Services.AddHostedService<TelegramBotService>();
|
||||
|
||||
// ── Session scheduler ────────────────────────────────────────────────
|
||||
builder.Services.AddHostedService<SessionSchedulerService>();
|
||||
builder.Services.AddHostedService<RescheduleVotingDeadlineService>();
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
}
|
||||
},
|
||||
"Telegram": {
|
||||
"BotToken": ""
|
||||
"BotToken": "",
|
||||
"MiniAppUrl": ""
|
||||
},
|
||||
"Web": {
|
||||
"BaseUrl": ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace GmRelay.Shared.Domain;
|
||||
|
||||
public enum CalendarSubscriptionFilter
|
||||
{
|
||||
AllMyGroups = 0,
|
||||
SpecificGroup = 1
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace GmRelay.Shared.Domain;
|
||||
|
||||
public enum GroupManagerRole
|
||||
{
|
||||
Owner,
|
||||
CoGm
|
||||
}
|
||||
|
||||
public static class GroupManagerRoleExtensions
|
||||
{
|
||||
public const string OwnerValue = "Owner";
|
||||
public const string CoGmValue = "CoGm";
|
||||
|
||||
public static string ToDatabaseValue(this GroupManagerRole role) => role switch
|
||||
{
|
||||
GroupManagerRole.Owner => OwnerValue,
|
||||
GroupManagerRole.CoGm => CoGmValue,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(role), role, "Unknown group manager role.")
|
||||
};
|
||||
|
||||
public static GroupManagerRole FromDatabaseValue(string value) => value switch
|
||||
{
|
||||
OwnerValue => GroupManagerRole.Owner,
|
||||
CoGmValue => GroupManagerRole.CoGm,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown group manager role.")
|
||||
};
|
||||
|
||||
public static string ToDisplayName(this GroupManagerRole role) => role switch
|
||||
{
|
||||
GroupManagerRole.Owner => "Owner",
|
||||
GroupManagerRole.CoGm => "Co-GM",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(role), role, "Unknown group manager role.")
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace GmRelay.Shared.Domain;
|
||||
|
||||
public enum SessionNotificationMode
|
||||
{
|
||||
GroupAndDirect,
|
||||
GroupOnly
|
||||
}
|
||||
|
||||
public static class SessionNotificationModeExtensions
|
||||
{
|
||||
public const string GroupAndDirectValue = nameof(SessionNotificationMode.GroupAndDirect);
|
||||
public const string GroupOnlyValue = nameof(SessionNotificationMode.GroupOnly);
|
||||
|
||||
public static bool ShouldSendDirectMessages(this SessionNotificationMode mode) =>
|
||||
mode == SessionNotificationMode.GroupAndDirect;
|
||||
|
||||
public static string ToDatabaseValue(this SessionNotificationMode mode) =>
|
||||
mode switch
|
||||
{
|
||||
SessionNotificationMode.GroupAndDirect => GroupAndDirectValue,
|
||||
SessionNotificationMode.GroupOnly => GroupOnlyValue,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown notification mode.")
|
||||
};
|
||||
|
||||
public static SessionNotificationMode FromDatabaseValue(string? value) =>
|
||||
value switch
|
||||
{
|
||||
null or "" => SessionNotificationMode.GroupAndDirect,
|
||||
GroupAndDirectValue => SessionNotificationMode.GroupAndDirect,
|
||||
GroupOnlyValue => SessionNotificationMode.GroupOnly,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown notification mode.")
|
||||
};
|
||||
}
|
||||
@@ -7,8 +7,4 @@
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Telegram.Bot" Version="22.9.5.3" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace GmRelay.Shared.Rendering;
|
||||
|
||||
/// <summary>
|
||||
/// Заглушка для Discord-рендерера.
|
||||
/// Реальная реализация будет добавлена в проект GmRelay.DiscordBot (issue #26).
|
||||
/// </summary>
|
||||
public static class DiscordSessionBatchRenderer
|
||||
{
|
||||
public static object Render(SessionBatchViewModel view)
|
||||
{
|
||||
throw new NotImplementedException("Discord renderer will be implemented in issue #26.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace GmRelay.Shared.Rendering;
|
||||
|
||||
public sealed record SessionBatchDto(Guid SessionId, DateTime ScheduledAt, string Status, int? MaxPlayers);
|
||||
public sealed record ParticipantBatchDto(Guid SessionId, string DisplayName, string? TelegramUsername, string RegistrationStatus);
|
||||
@@ -1,90 +0,0 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Shared.Rendering;
|
||||
|
||||
public sealed record SessionBatchDto(Guid SessionId, DateTime ScheduledAt, string Status, int? MaxPlayers);
|
||||
public sealed record ParticipantBatchDto(Guid SessionId, string DisplayName, string? TelegramUsername, string RegistrationStatus);
|
||||
|
||||
public static class SessionBatchRenderer
|
||||
{
|
||||
public static (string Text, InlineKeyboardMarkup Markup) Render(
|
||||
string title,
|
||||
IReadOnlyList<SessionBatchDto> sessions,
|
||||
IReadOnlyList<ParticipantBatchDto> participants)
|
||||
{
|
||||
var activeSessions = sessions.OrderBy(s => s.ScheduledAt).ToList();
|
||||
|
||||
var messageText = $"🎲 <b>Новые игры:</b> {System.Net.WebUtility.HtmlEncode(title)}\n\n" +
|
||||
$"<b>Расписание:</b>\n\n";
|
||||
|
||||
var buttons = new List<InlineKeyboardButton[]>();
|
||||
|
||||
foreach (var session in activeSessions)
|
||||
{
|
||||
var sessionPlayers = participants
|
||||
.Where(p => p.SessionId == session.SessionId && p.RegistrationStatus == ParticipantRegistrationStatus.Active)
|
||||
.ToList();
|
||||
var waitlistedPlayers = participants
|
||||
.Where(p => p.SessionId == session.SessionId && p.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted)
|
||||
.ToList();
|
||||
|
||||
messageText += $"📅 <b>{session.ScheduledAt.FormatMoscow()}</b>\n";
|
||||
messageText += session.MaxPlayers.HasValue
|
||||
? $"👥 Места: {sessionPlayers.Count}/{session.MaxPlayers.Value}\n"
|
||||
: $"👥 Игроки ({sessionPlayers.Count}):\n";
|
||||
|
||||
if (sessionPlayers.Count > 0)
|
||||
{
|
||||
messageText += string.Join("\n", sessionPlayers.Select(p => $" 👤 {(p.TelegramUsername != null ? "@" + p.TelegramUsername : p.DisplayName)}")) + "\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
messageText += " <i>Пока никто не записался</i>\n";
|
||||
}
|
||||
|
||||
if (waitlistedPlayers.Count > 0)
|
||||
{
|
||||
messageText += $"⏳ Лист ожидания ({waitlistedPlayers.Count}):\n";
|
||||
messageText += string.Join("\n", waitlistedPlayers.Select(p => $" ⏱ {(p.TelegramUsername != null ? "@" + p.TelegramUsername : p.DisplayName)}")) + "\n";
|
||||
}
|
||||
|
||||
if (SessionStatus.IsCancelled(session.Status))
|
||||
{
|
||||
messageText += "❌ <i>Сессия отменена</i>\n\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
messageText += "\n";
|
||||
var dateTitle = session.ScheduledAt.FormatMoscowShort();
|
||||
buttons.Add(new[]
|
||||
{
|
||||
InlineKeyboardButton.WithCallbackData(GetJoinButtonText(session, sessionPlayers.Count, dateTitle), $"join_session:{session.SessionId}"),
|
||||
InlineKeyboardButton.WithCallbackData($"🚪 Выйти {dateTitle}", $"leave_session:{session.SessionId}")
|
||||
});
|
||||
|
||||
buttons.Add(new[]
|
||||
{
|
||||
InlineKeyboardButton.WithCallbackData($"❌ Отменить {dateTitle} (ГМ)", $"cancel_session:{session.SessionId}"),
|
||||
InlineKeyboardButton.WithCallbackData($"⏰ (ГМ)", $"reschedule_session:{session.SessionId}")
|
||||
}
|
||||
.Concat(SessionCapacityRules.CanPromoteWaitlistedPlayer(session.MaxPlayers, sessionPlayers.Count, waitlistedPlayers.Count)
|
||||
? [InlineKeyboardButton.WithCallbackData($"⬆️ Из ожидания {dateTitle} (ГМ)", $"promote_waitlist:{session.SessionId}")]
|
||||
: [])
|
||||
.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
return (messageText, new InlineKeyboardMarkup(buttons));
|
||||
}
|
||||
|
||||
private static string GetJoinButtonText(SessionBatchDto session, int activePlayers, string dateTitle)
|
||||
{
|
||||
if (session.MaxPlayers.HasValue && activePlayers >= session.MaxPlayers.Value)
|
||||
{
|
||||
return $"⏳ В лист ожидания {dateTitle}";
|
||||
}
|
||||
|
||||
return $"✋ На {dateTitle}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Shared.Rendering;
|
||||
|
||||
public static class SessionBatchViewBuilder
|
||||
{
|
||||
public static SessionBatchViewModel Build(
|
||||
string title,
|
||||
IReadOnlyList<SessionBatchDto> sessions,
|
||||
IReadOnlyList<ParticipantBatchDto> participants)
|
||||
{
|
||||
var orderedSessions = sessions.OrderBy(s => s.ScheduledAt).ToList();
|
||||
var sessionItems = new List<SessionViewItem>();
|
||||
|
||||
foreach (var session in orderedSessions)
|
||||
{
|
||||
var activePlayers = participants
|
||||
.Where(p => p.SessionId == session.SessionId && p.RegistrationStatus == ParticipantRegistrationStatus.Active)
|
||||
.Select(p => new PlayerViewItem(p.DisplayName, p.TelegramUsername, p.RegistrationStatus))
|
||||
.ToList();
|
||||
|
||||
var waitlistedPlayers = participants
|
||||
.Where(p => p.SessionId == session.SessionId && p.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted)
|
||||
.Select(p => new PlayerViewItem(p.DisplayName, p.TelegramUsername, p.RegistrationStatus))
|
||||
.ToList();
|
||||
|
||||
var actions = new List<AvailableAction>();
|
||||
if (!SessionStatus.IsCancelled(session.Status))
|
||||
{
|
||||
var dateTitle = session.ScheduledAt.FormatMoscowShort();
|
||||
var joinLabel = GetJoinButtonText(session, activePlayers.Count, dateTitle);
|
||||
actions.Add(new AvailableAction("join_session", joinLabel, session.SessionId));
|
||||
actions.Add(new AvailableAction("leave_session", $"🚪 Выйти {dateTitle}", session.SessionId));
|
||||
}
|
||||
|
||||
sessionItems.Add(new SessionViewItem(
|
||||
session.SessionId,
|
||||
session.ScheduledAt,
|
||||
session.Status,
|
||||
session.MaxPlayers,
|
||||
activePlayers.Count,
|
||||
activePlayers,
|
||||
waitlistedPlayers,
|
||||
actions));
|
||||
}
|
||||
|
||||
return new SessionBatchViewModel(title, sessionItems);
|
||||
}
|
||||
|
||||
private static string GetJoinButtonText(SessionBatchDto session, int activePlayers, string dateTitle)
|
||||
{
|
||||
if (session.MaxPlayers.HasValue && activePlayers >= session.MaxPlayers.Value)
|
||||
{
|
||||
return $"⏳ В лист ожидания {dateTitle}";
|
||||
}
|
||||
|
||||
return $"✋ На {dateTitle}";
|
||||
}
|
||||
}
|
||||
// trigger pr
|
||||
@@ -0,0 +1,27 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Shared.Rendering;
|
||||
|
||||
public sealed record SessionBatchViewModel(
|
||||
string Title,
|
||||
IReadOnlyList<SessionViewItem> Sessions);
|
||||
|
||||
public sealed record SessionViewItem(
|
||||
Guid SessionId,
|
||||
DateTime ScheduledAt,
|
||||
string Status,
|
||||
int? MaxPlayers,
|
||||
int ActivePlayerCount,
|
||||
IReadOnlyList<PlayerViewItem> ActivePlayers,
|
||||
IReadOnlyList<PlayerViewItem> WaitlistedPlayers,
|
||||
IReadOnlyList<AvailableAction> AvailableActions);
|
||||
|
||||
public sealed record PlayerViewItem(
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
string RegistrationStatus);
|
||||
|
||||
public sealed record AvailableAction(
|
||||
string ActionKey,
|
||||
string Label,
|
||||
Guid SessionId);
|
||||
@@ -13,6 +13,7 @@
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="@Assets["app.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["GmRelay.Web.styles.css"]" />
|
||||
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
||||
<ImportMap />
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<HeadOutlet @rendermode="InteractiveServer" />
|
||||
@@ -23,19 +24,275 @@
|
||||
<ReconnectModal />
|
||||
<script src="@Assets["_framework/blazor.web.js"]"></script>
|
||||
<script>
|
||||
window.waitForTelegramMiniApp = async function (timeoutMs) {
|
||||
var deadline = Date.now() + (timeoutMs || 3000);
|
||||
|
||||
while (Date.now() <= deadline) {
|
||||
if (window.Telegram && window.Telegram.WebApp) {
|
||||
return window.Telegram.WebApp;
|
||||
}
|
||||
|
||||
await new Promise(function (resolve) {
|
||||
setTimeout(resolve, 100);
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
window.waitForTelegramMiniAppInitData = async function (timeoutMs) {
|
||||
var deadline = Date.now() + (timeoutMs || 3000);
|
||||
|
||||
while (Date.now() <= deadline) {
|
||||
if (window.Telegram && window.Telegram.WebApp && window.Telegram.WebApp.initData) {
|
||||
return window.Telegram.WebApp;
|
||||
}
|
||||
|
||||
await new Promise(function (resolve) {
|
||||
setTimeout(resolve, 100);
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
window.syncTelegramMiniAppViewport = function (webApp) {
|
||||
if (!webApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
var root = document.documentElement;
|
||||
var safeArea = webApp.safeAreaInset || {};
|
||||
var contentSafeArea = webApp.contentSafeAreaInset || {};
|
||||
var setPx = function (name, value) {
|
||||
root.style.setProperty(name, Math.max(0, Number(value) || 0) + 'px');
|
||||
};
|
||||
|
||||
setPx('--gm-tg-safe-top', safeArea.top);
|
||||
setPx('--gm-tg-safe-right', safeArea.right);
|
||||
setPx('--gm-tg-safe-bottom', safeArea.bottom);
|
||||
setPx('--gm-tg-safe-left', safeArea.left);
|
||||
setPx('--gm-tg-content-safe-top', contentSafeArea.top);
|
||||
setPx('--gm-tg-content-safe-right', contentSafeArea.right);
|
||||
setPx('--gm-tg-content-safe-bottom', contentSafeArea.bottom);
|
||||
setPx('--gm-tg-content-safe-left', contentSafeArea.left);
|
||||
|
||||
if (webApp.viewportHeight) {
|
||||
root.style.setProperty('--gm-tg-viewport-height', webApp.viewportHeight + 'px');
|
||||
}
|
||||
};
|
||||
|
||||
window.prepareTelegramMiniApp = function (webApp) {
|
||||
if (!webApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
document.body.classList.add('telegram-mini-app');
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
|
||||
try {
|
||||
webApp.ready();
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
try {
|
||||
webApp.expand();
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
if (webApp.onEvent && !window.gmRelayTelegramMiniAppViewportEventsRegistered) {
|
||||
window.gmRelayTelegramMiniAppViewportEventsRegistered = true;
|
||||
webApp.onEvent('safeAreaChanged', function () {
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
});
|
||||
webApp.onEvent('contentSafeAreaChanged', function () {
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
});
|
||||
webApp.onEvent('viewportChanged', function () {
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
(async function () {
|
||||
var webApp = await window.waitForTelegramMiniApp(1000);
|
||||
window.prepareTelegramMiniApp(webApp);
|
||||
})();
|
||||
|
||||
window.loadTelegramWidget = function (botUsername, authUrl) {
|
||||
var container = document.getElementById('telegram-login-container');
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
window.gmRelayTelegramLoginAuthUrl = authUrl || '/auth/telegram-login';
|
||||
var script = document.createElement('script');
|
||||
script.async = true;
|
||||
script.src = 'https://telegram.org/js/telegram-widget.js?22';
|
||||
script.setAttribute('data-telegram-login', botUsername);
|
||||
script.setAttribute('data-size', 'large');
|
||||
script.setAttribute('data-auth-url', authUrl);
|
||||
script.setAttribute('data-onauth', 'window.handleTelegramLogin(user)');
|
||||
script.setAttribute('data-request-access', 'write');
|
||||
container.appendChild(script);
|
||||
};
|
||||
|
||||
window.handleTelegramLogin = async function (user) {
|
||||
if (!user) {
|
||||
window.location.href = '/login?error=auth_failed';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var response = await fetch(window.gmRelayTelegramLoginAuthUrl || '/auth/telegram-login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
body: JSON.stringify(user)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
window.location.href = '/login?error=auth_failed';
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = await response.json();
|
||||
window.location.href = payload.redirectUrl || '/';
|
||||
} catch (error) {
|
||||
window.location.href = '/login?error=auth_failed';
|
||||
}
|
||||
};
|
||||
|
||||
window.watchTelegramMiniAppLogin = function (statusUrl, redirectUrl, reloadOnReturn) {
|
||||
window.gmRelayMiniAppLoginReloadOnReturn =
|
||||
window.gmRelayMiniAppLoginReloadOnReturn || reloadOnReturn === true;
|
||||
|
||||
if (window.gmRelayMiniAppLoginWatcher) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.gmRelayMiniAppLoginLeftPage = false;
|
||||
|
||||
var stopWatching = function () {
|
||||
if (window.gmRelayMiniAppLoginWatcher) {
|
||||
window.clearInterval(window.gmRelayMiniAppLoginWatcher);
|
||||
window.gmRelayMiniAppLoginWatcher = null;
|
||||
}
|
||||
};
|
||||
|
||||
var reloadAfterExternalLogin = function () {
|
||||
if (!window.gmRelayMiniAppLoginReloadOnReturn || !window.gmRelayMiniAppLoginLeftPage) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.gmRelayMiniAppLoginLeftPage = false;
|
||||
|
||||
try {
|
||||
var refreshKey = 'gmrelay-miniapp-login-refresh:' + window.location.pathname;
|
||||
if (window.sessionStorage && window.sessionStorage.getItem(refreshKey) === '1') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.sessionStorage) {
|
||||
window.sessionStorage.setItem(refreshKey, '1');
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
var allowNextExternalLoginReload = function () {
|
||||
window.gmRelayMiniAppLoginLeftPage = true;
|
||||
|
||||
try {
|
||||
var refreshKey = 'gmrelay-miniapp-login-refresh:' + window.location.pathname;
|
||||
if (window.sessionStorage) {
|
||||
window.sessionStorage.removeItem(refreshKey);
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
};
|
||||
|
||||
var checkLogin = async function (reloadWhenUnauthenticated) {
|
||||
try {
|
||||
var response = await fetch(statusUrl, {
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = await response.json();
|
||||
if (payload.authenticated) {
|
||||
stopWatching();
|
||||
window.location.href = redirectUrl || '/';
|
||||
return;
|
||||
}
|
||||
|
||||
if (reloadWhenUnauthenticated) {
|
||||
reloadAfterExternalLogin();
|
||||
}
|
||||
} catch (error) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
window.gmRelayMiniAppLoginWatcher = window.setInterval(checkLogin, 1000);
|
||||
window.addEventListener('blur', function () {
|
||||
allowNextExternalLoginReload();
|
||||
});
|
||||
window.addEventListener('focus', function () {
|
||||
void checkLogin(true);
|
||||
});
|
||||
document.addEventListener('visibilitychange', function () {
|
||||
if (document.hidden) {
|
||||
allowNextExternalLoginReload();
|
||||
return;
|
||||
}
|
||||
|
||||
void checkLogin(true);
|
||||
});
|
||||
|
||||
void checkLogin(false);
|
||||
};
|
||||
|
||||
window.authenticateTelegramMiniApp = async function (authUrl, redirectUrl) {
|
||||
var webApp = await window.waitForTelegramMiniApp(3000);
|
||||
if (!webApp) {
|
||||
return { authenticated: false, reason: 'telegram-webapp-missing' };
|
||||
}
|
||||
|
||||
window.prepareTelegramMiniApp(webApp);
|
||||
|
||||
if (!webApp.initData) {
|
||||
return { authenticated: false, reason: 'telegram-init-data-empty' };
|
||||
}
|
||||
|
||||
try {
|
||||
var response = await fetch(authUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
body: JSON.stringify({ initData: webApp.initData })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
authenticated: false,
|
||||
reason: 'telegram-auth-failed',
|
||||
status: response.status
|
||||
};
|
||||
}
|
||||
|
||||
var payload = await response.json();
|
||||
window.location.href = payload.redirectUrl || redirectUrl || '/';
|
||||
return { authenticated: true, redirectUrl: payload.redirectUrl || redirectUrl || '/' };
|
||||
} catch (error) {
|
||||
return { authenticated: false, reason: 'telegram-auth-failed' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
|
||||
|
||||
@@ -60,12 +60,17 @@
|
||||
/* === Mobile Responsive === */
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
transform: translateX(-100%);
|
||||
width: 280px;
|
||||
transform: none;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
position: sticky;
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.sidebar.open {
|
||||
transform: translateX(0);
|
||||
.page {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.main-area {
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
<div class="nav-header">
|
||||
<a class="nav-brand" href="">
|
||||
<span class="nav-brand-icon">🎲</span>
|
||||
<span class="nav-brand-icon">🐢</span>
|
||||
<span class="nav-brand-text">GM-Relay</span>
|
||||
</a>
|
||||
<button class="nav-toggle" @onclick="ToggleMenu" aria-label="Навигационное меню">
|
||||
<button class="nav-toggle" @onclick="ToggleMenu" aria-label="Переключить меню">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<line x1="3" y1="6" x2="21" y2="6"/>
|
||||
<line x1="3" y1="12" x2="21" y2="12"/>
|
||||
@@ -23,7 +23,16 @@
|
||||
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
|
||||
<polyline points="9 22 9 12 15 12 15 22"/>
|
||||
</svg>
|
||||
Панель управления
|
||||
Главная страница
|
||||
</NavLink>
|
||||
<NavLink class="nav-item" href="templates" @onclick="CloseMenu">
|
||||
<svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="4" width="18" height="16" rx="2"/>
|
||||
<path d="M7 8h10"/>
|
||||
<path d="M7 12h6"/>
|
||||
<path d="M7 16h8"/>
|
||||
</svg>
|
||||
Шаблоны
|
||||
</NavLink>
|
||||
</div>
|
||||
|
||||
@@ -43,11 +52,11 @@
|
||||
<polyline points="16 17 21 12 16 7"/>
|
||||
<line x1="21" y1="12" x2="9" y2="12"/>
|
||||
</svg>
|
||||
Выйти
|
||||
Выход
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="nav-version">v1.3.0</div>
|
||||
<div class="nav-version">v1.10.2</div>
|
||||
</div>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
@@ -58,7 +67,7 @@
|
||||
<polyline points="10 17 15 12 10 7"/>
|
||||
<line x1="15" y1="12" x2="3" y2="12"/>
|
||||
</svg>
|
||||
Войти
|
||||
Вход
|
||||
</NavLink>
|
||||
</div>
|
||||
</NotAuthorized>
|
||||
|
||||
@@ -56,13 +56,17 @@
|
||||
.nav-section {
|
||||
padding: 0 0.75rem;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* === Nav Items === */
|
||||
.nav-item {
|
||||
.nav-section ::deep .nav-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-secondary);
|
||||
@@ -70,16 +74,16 @@
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
transition: all var(--transition-normal);
|
||||
margin-bottom: 0.125rem;
|
||||
white-space: nowrap;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.nav-item:hover {
|
||||
.nav-section ::deep .nav-item:hover {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.nav-item.active,
|
||||
.nav-item ::deep a.active {
|
||||
.nav-section ::deep .nav-item.active {
|
||||
background: rgba(124, 58, 237, 0.15);
|
||||
color: var(--accent-primary);
|
||||
border: 1px solid rgba(124, 58, 237, 0.2);
|
||||
@@ -180,6 +184,14 @@
|
||||
|
||||
.nav-body.open {
|
||||
display: flex;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 200;
|
||||
background: linear-gradient(180deg, #0f1629 0%, #1a0a2e 100%);
|
||||
padding-top: 4.5rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
.nav-header {
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
@page "/templates"
|
||||
@using GmRelay.Web.Services
|
||||
@using GmRelay.Shared.Domain
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@attribute [Authorize]
|
||||
@inject AuthorizedSessionService SessionService
|
||||
@inject AuthenticationStateProvider AuthStateProvider
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Шаблоны кампаний — GM-Relay</PageTitle>
|
||||
|
||||
<div class="page-container">
|
||||
<ul class="gm-breadcrumb animate-fade-in">
|
||||
<li><a href="/">Главная</a></li>
|
||||
<li class="active">Шаблоны кампаний</li>
|
||||
</ul>
|
||||
|
||||
<div class="page-header animate-fade-in">
|
||||
<h2>📋 Шаблоны кампаний</h2>
|
||||
<p>Сохраняйте типовые кампании один раз и применяйте их на странице нужной группы.</p>
|
||||
</div>
|
||||
|
||||
@if (!string.IsNullOrEmpty(errorMessage))
|
||||
{
|
||||
<div class="gm-alert gm-alert-danger" style="margin-bottom: 1rem;">
|
||||
⚠️ @errorMessage
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(successMessage))
|
||||
{
|
||||
<div class="gm-alert gm-alert-success" style="margin-bottom: 1rem;">
|
||||
✅ @successMessage
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (groups is null)
|
||||
{
|
||||
<div class="glass-card" style="padding: 2rem;">
|
||||
<div class="skeleton skeleton-text" style="width: 80%; margin-bottom: 1rem;"></div>
|
||||
<div class="skeleton skeleton-text" style="width: 60%; margin-bottom: 0.75rem;"></div>
|
||||
<div class="skeleton skeleton-text" style="width: 70%;"></div>
|
||||
</div>
|
||||
}
|
||||
else if (groups.Count == 0)
|
||||
{
|
||||
<div class="glass-card">
|
||||
<div class="empty-state">
|
||||
<div class="empty-state-icon">🤖</div>
|
||||
<div class="empty-state-title">Нет доступных групп</div>
|
||||
<p class="empty-state-text">Добавьте бота GM-Relay в группу Telegram, чтобы создать первый шаблон кампании.</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="glass-card campaign-template-panel animate-slide-up">
|
||||
<div class="batch-bulk-header">
|
||||
<div>
|
||||
<h3>Группа для шаблонов</h3>
|
||||
<p>@(SelectedGroup?.Name ?? "Выберите группу")</p>
|
||||
</div>
|
||||
@if (SelectedGroup is not null)
|
||||
{
|
||||
<span class="status-badge @(SelectedGroup.ManagerRole == GroupManagerRoleExtensions.OwnerValue ? "status-success" : "status-info")">
|
||||
@FormatRole(SelectedGroup.ManagerRole)
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="template-group-selector">
|
||||
<select value="@selectedGroupId" @onchange="OnSelectedGroupChanged" class="gm-form-control">
|
||||
@foreach (var group in groups)
|
||||
{
|
||||
<option value="@group.Id">@group.Name</option>
|
||||
}
|
||||
</select>
|
||||
@if (SelectedGroup is not null)
|
||||
{
|
||||
<a href="/group/@SelectedGroup.Id" class="btn-gm btn-gm-outline">Открыть группу →</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="glass-card campaign-template-panel animate-slide-up">
|
||||
<div class="batch-bulk-header">
|
||||
<div>
|
||||
<h3>Новый шаблон</h3>
|
||||
<p>Эти параметры будут использоваться при запуске batch из группы.</p>
|
||||
</div>
|
||||
<span class="status-badge status-info">Template</span>
|
||||
</div>
|
||||
|
||||
<EditForm Model="@templateModel" OnValidSubmit="CreateCampaignTemplate">
|
||||
<div class="campaign-template-fields">
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Название шаблона</label>
|
||||
<InputText @bind-Value="templateModel.Name" class="gm-form-control" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Название кампании</label>
|
||||
<InputText @bind-Value="templateModel.Title" class="gm-form-control" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Ссылка</label>
|
||||
<InputText @bind-Value="templateModel.JoinLink" class="gm-form-control" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Игр</label>
|
||||
<InputNumber @bind-Value="templateModel.SessionCount" class="gm-form-control" min="1" max="52" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Интервал, дней</label>
|
||||
<InputNumber @bind-Value="templateModel.IntervalDays" class="gm-form-control" min="1" max="365" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Мест</label>
|
||||
<InputNumber @bind-Value="templateModel.MaxPlayers" class="gm-form-control" min="1" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Уведомления</label>
|
||||
<select @bind="templateModel.NotificationMode" class="gm-form-control">
|
||||
<option value="@SessionNotificationModeExtensions.GroupAndDirectValue">В группе и в личку</option>
|
||||
<option value="@SessionNotificationModeExtensions.GroupOnlyValue">Только в группе</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn-gm btn-gm-primary" disabled="@isCreatingTemplate">
|
||||
@(isCreatingTemplate ? "⏳ Сохраняем..." : "💾 Сохранить шаблон")
|
||||
</button>
|
||||
</EditForm>
|
||||
</div>
|
||||
|
||||
<div class="glass-card campaign-template-panel animate-slide-up">
|
||||
<div class="batch-bulk-header">
|
||||
<div>
|
||||
<h3>Сохранённые шаблоны</h3>
|
||||
<p>@campaignTemplateModels.Count для выбранной группы</p>
|
||||
</div>
|
||||
<span class="status-badge status-info">@campaignTemplateModels.Count</span>
|
||||
</div>
|
||||
|
||||
@if (campaignTemplates is null)
|
||||
{
|
||||
<div class="skeleton skeleton-text" style="width: 70%; margin-bottom: 0.75rem;"></div>
|
||||
<div class="skeleton skeleton-text" style="width: 55%;"></div>
|
||||
}
|
||||
else if (campaignTemplateModels.Count == 0)
|
||||
{
|
||||
<div class="empty-state empty-state-compact">
|
||||
<div class="empty-state-title">Шаблонов пока нет</div>
|
||||
<p class="empty-state-text">Создайте первый шаблон для выбранной группы.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="campaign-template-list">
|
||||
@foreach (var template in campaignTemplateModels)
|
||||
{
|
||||
<div class="campaign-template-row template-management-row">
|
||||
<div class="campaign-template-info">
|
||||
<h3>@template.Name</h3>
|
||||
<p>@FormatTemplateSummary(template)</p>
|
||||
</div>
|
||||
<div class="template-management-actions">
|
||||
<span class="status-badge status-neutral">@FormatLocalMoscow(template.UpdatedAt.ToMoscow())</span>
|
||||
<button type="button" class="btn-gm btn-gm-danger" disabled="@(deletingTemplateId == template.Id)" @onclick="() => DeleteCampaignTemplate(template)">
|
||||
@(deletingTemplateId == template.Id ? "⏳ Удаляем..." : "Удалить")
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private List<WebGameGroup>? groups;
|
||||
private List<WebCampaignTemplate>? campaignTemplates;
|
||||
private List<CampaignTemplateManagementModel> campaignTemplateModels = [];
|
||||
private Guid selectedGroupId;
|
||||
private Guid? deletingTemplateId;
|
||||
private bool isCreatingTemplate;
|
||||
private long telegramId;
|
||||
private string? errorMessage;
|
||||
private string? successMessage;
|
||||
private CampaignTemplateEditModel templateModel = new();
|
||||
|
||||
private WebGameGroup? SelectedGroup => groups?.FirstOrDefault(group => group.Id == selectedGroupId);
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
|
||||
if (!authState.User.TryGetTelegramId(out telegramId))
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
|
||||
groups = await SessionService.GetGroupsForGmAsync(telegramId);
|
||||
selectedGroupId = groups.FirstOrDefault()?.Id ?? Guid.Empty;
|
||||
|
||||
if (selectedGroupId != Guid.Empty)
|
||||
{
|
||||
await LoadTemplates();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnSelectedGroupChanged(ChangeEventArgs args)
|
||||
{
|
||||
if (!Guid.TryParse(args.Value?.ToString(), out var groupId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
selectedGroupId = groupId;
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
await LoadTemplates();
|
||||
}
|
||||
|
||||
private async Task LoadTemplates()
|
||||
{
|
||||
campaignTemplates = null;
|
||||
campaignTemplateModels = [];
|
||||
|
||||
var templates = await SessionService.GetCampaignTemplatesForGmAsync(selectedGroupId, telegramId);
|
||||
if (templates is null)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
|
||||
campaignTemplates = templates;
|
||||
RebuildCampaignTemplateModels();
|
||||
}
|
||||
|
||||
private async Task CreateCampaignTemplate()
|
||||
{
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
|
||||
if (selectedGroupId == Guid.Empty)
|
||||
{
|
||||
errorMessage = "Выберите группу для шаблона.";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ValidateCampaignTemplate(templateModel))
|
||||
{
|
||||
errorMessage = "Шаблон должен иметь название, ссылку, 1-52 игр, шаг 1-365 дней и положительный лимит мест, если он указан.";
|
||||
return;
|
||||
}
|
||||
|
||||
isCreatingTemplate = true;
|
||||
|
||||
try
|
||||
{
|
||||
await SessionService.CreateCampaignTemplateForGmAsync(
|
||||
selectedGroupId,
|
||||
telegramId,
|
||||
new CreateCampaignTemplateRequest(
|
||||
templateModel.Name,
|
||||
templateModel.Title,
|
||||
templateModel.JoinLink,
|
||||
templateModel.SessionCount,
|
||||
templateModel.IntervalDays,
|
||||
templateModel.MaxPlayers,
|
||||
SessionNotificationModeExtensions.FromDatabaseValue(templateModel.NotificationMode)));
|
||||
|
||||
templateModel = new();
|
||||
successMessage = "Шаблон кампании сохранён.";
|
||||
await LoadTemplates();
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = "Не удалось сохранить шаблон: " + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
isCreatingTemplate = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DeleteCampaignTemplate(CampaignTemplateManagementModel template)
|
||||
{
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
deletingTemplateId = template.Id;
|
||||
|
||||
try
|
||||
{
|
||||
await SessionService.DeleteCampaignTemplateForGmAsync(template.Id, telegramId);
|
||||
successMessage = "Шаблон кампании удалён.";
|
||||
await LoadTemplates();
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = "Не удалось удалить шаблон: " + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
deletingTemplateId = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void RebuildCampaignTemplateModels()
|
||||
{
|
||||
campaignTemplateModels = campaignTemplates?
|
||||
.OrderByDescending(template => template.UpdatedAt)
|
||||
.ThenBy(template => template.Name)
|
||||
.Select(template => new CampaignTemplateManagementModel
|
||||
{
|
||||
Id = template.Id,
|
||||
Name = template.Name,
|
||||
Title = template.Title,
|
||||
JoinLink = template.JoinLink,
|
||||
SessionCount = template.SessionCount,
|
||||
IntervalDays = template.IntervalDays,
|
||||
MaxPlayers = template.MaxPlayers,
|
||||
NotificationMode = template.NotificationMode,
|
||||
UpdatedAt = template.UpdatedAt
|
||||
})
|
||||
.ToList() ?? [];
|
||||
}
|
||||
|
||||
private static bool ValidateCampaignTemplate(CampaignTemplateEditModel template)
|
||||
{
|
||||
template.Name = template.Name.Trim();
|
||||
template.Title = template.Title.Trim();
|
||||
template.JoinLink = template.JoinLink.Trim();
|
||||
|
||||
if (template.MaxPlayers.HasValue && template.MaxPlayers.Value <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return template.Name.Length > 0 &&
|
||||
template.Title.Length > 0 &&
|
||||
template.JoinLink.Length > 0 &&
|
||||
template.SessionCount is >= 1 and <= 52 &&
|
||||
template.IntervalDays is >= 1 and <= 365;
|
||||
}
|
||||
|
||||
private static string FormatTemplateSummary(CampaignTemplateManagementModel template)
|
||||
{
|
||||
var seats = template.MaxPlayers.HasValue
|
||||
? $"{template.MaxPlayers.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)} мест"
|
||||
: "без лимита";
|
||||
|
||||
return $"{template.Title} · {template.SessionCount} игр · каждые {template.IntervalDays} дн. · {seats} · {FormatNotificationMode(template.NotificationMode)}";
|
||||
}
|
||||
|
||||
private static string FormatNotificationMode(string notificationMode) =>
|
||||
SessionNotificationModeExtensions.FromDatabaseValue(notificationMode) switch
|
||||
{
|
||||
SessionNotificationMode.GroupOnly => "только группа",
|
||||
_ => "группа и личка"
|
||||
};
|
||||
|
||||
private static string FormatRole(string role) =>
|
||||
GroupManagerRoleExtensions.FromDatabaseValue(role).ToDisplayName();
|
||||
|
||||
private static string FormatLocalMoscow(DateTime localMoscow) =>
|
||||
localMoscow.ToString("d MMMM yyyy, HH:mm", System.Globalization.CultureInfo.GetCultureInfo("ru-RU"));
|
||||
|
||||
private sealed class CampaignTemplateEditModel
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string Title { get; set; } = "";
|
||||
public string JoinLink { get; set; } = "";
|
||||
public int SessionCount { get; set; } = 6;
|
||||
public int IntervalDays { get; set; } = 7;
|
||||
public int? MaxPlayers { get; set; }
|
||||
public string NotificationMode { get; set; } = SessionNotificationModeExtensions.GroupAndDirectValue;
|
||||
}
|
||||
|
||||
private sealed class CampaignTemplateManagementModel
|
||||
{
|
||||
public Guid Id { get; init; }
|
||||
public string Name { get; init; } = "";
|
||||
public string Title { get; init; } = "";
|
||||
public string JoinLink { get; init; } = "";
|
||||
public int SessionCount { get; init; }
|
||||
public int IntervalDays { get; init; }
|
||||
public int? MaxPlayers { get; init; }
|
||||
public string NotificationMode { get; init; } = SessionNotificationModeExtensions.GroupAndDirectValue;
|
||||
public DateTime UpdatedAt { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,58 @@
|
||||
<h2>📅 Предстоящие игры</h2>
|
||||
</div>
|
||||
|
||||
@if (groupManagement is not null)
|
||||
{
|
||||
<div class="glass-card animate-slide-up" style="margin-bottom: 1rem;">
|
||||
<div class="batch-bulk-header">
|
||||
<div>
|
||||
<h3>Управление группой</h3>
|
||||
<p>@groupManagement.Group.Name · @FormatRole(CurrentUserRole)</p>
|
||||
</div>
|
||||
<span class="status-badge status-info">@FormatRole(CurrentUserRole)</span>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 1rem;">
|
||||
<a href="/groupstats/@GroupId" class="btn-gm btn-gm-outline">📊 Статистика</a>
|
||||
@foreach (var manager in groupManagement.Managers)
|
||||
{
|
||||
<span class="status-badge @(manager.Role == GroupManagerRoleExtensions.OwnerValue ? "status-success" : "status-info")">
|
||||
@FormatManager(manager)
|
||||
</span>
|
||||
@if (groupManagement.CurrentUserIsOwner && manager.Role == GroupManagerRoleExtensions.CoGmValue)
|
||||
{
|
||||
<button type="button" class="btn-gm btn-gm-outline" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;" disabled="@(removingCoGmId == manager.TelegramId)" @onclick="() => RemoveCoGm(manager.TelegramId)">
|
||||
@(removingCoGmId == manager.TelegramId ? "⏳ Удаляем..." : "Убрать")
|
||||
</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (groupManagement.CurrentUserIsOwner)
|
||||
{
|
||||
<EditForm Model="@coGmModel" OnValidSubmit="AddCoGm">
|
||||
<div class="batch-bulk-fields">
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Telegram ID co-GM</label>
|
||||
<InputNumber @bind-Value="coGmModel.TelegramId" class="gm-form-control" min="1" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Имя</label>
|
||||
<InputText @bind-Value="coGmModel.DisplayName" class="gm-form-control" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Username</label>
|
||||
<InputText @bind-Value="coGmModel.TelegramUsername" class="gm-form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn-gm btn-gm-primary" disabled="@isAddingCoGm">
|
||||
@(isAddingCoGm ? "⏳ Добавляем..." : "➕ Добавить co-GM")
|
||||
</button>
|
||||
</EditForm>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(errorMessage))
|
||||
{
|
||||
<div class="gm-alert gm-alert-danger" style="margin-bottom: 1rem;">
|
||||
@@ -34,6 +86,47 @@
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (campaignTemplates is not null)
|
||||
{
|
||||
<div class="glass-card campaign-template-panel animate-slide-up">
|
||||
<div class="batch-bulk-header">
|
||||
<div>
|
||||
<h3>Применить шаблон</h3>
|
||||
<p>@campaignTemplateModels.Count доступных для этой группы</p>
|
||||
</div>
|
||||
<a href="/templates" class="btn-gm btn-gm-outline">⚙️ Управлять шаблонами</a>
|
||||
</div>
|
||||
|
||||
@if (campaignTemplateModels.Count == 0)
|
||||
{
|
||||
<div class="empty-state empty-state-compact">
|
||||
<div class="empty-state-title">Шаблонов пока нет</div>
|
||||
<p class="empty-state-text">Создайте шаблоны в отдельной вкладке, а здесь запускайте из них новые batch-расписания.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="campaign-template-list">
|
||||
@foreach (var template in campaignTemplateModels)
|
||||
{
|
||||
<div class="campaign-template-row">
|
||||
<div class="campaign-template-info">
|
||||
<h3>@template.Name</h3>
|
||||
<p>@FormatTemplateSummary(template)</p>
|
||||
</div>
|
||||
<div class="campaign-template-actions">
|
||||
<input type="datetime-local" @bind="template.FirstScheduledAtLocal" class="gm-form-control" />
|
||||
<button type="button" class="btn-gm btn-gm-success" disabled="@IsTemplateBusy(template)" @onclick="() => CreateBatchFromTemplate(template)">
|
||||
@(processingTemplateId == template.Id ? "⏳ Создаём..." : "📅 Создать batch")
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (sessions == null)
|
||||
{
|
||||
<div class="glass-card" style="padding: 2rem;">
|
||||
@@ -77,9 +170,16 @@
|
||||
<label class="gm-form-label">Общая ссылка</label>
|
||||
<InputText @bind-Value="batch.JoinLink" class="gm-form-control" />
|
||||
</div>
|
||||
<div class="gm-form-group">
|
||||
<label class="gm-form-label">Уведомления игрокам</label>
|
||||
<select @bind="batch.NotificationMode" class="gm-form-control">
|
||||
<option value="@SessionNotificationModeExtensions.GroupAndDirectValue">В группе и в личку</option>
|
||||
<option value="@SessionNotificationModeExtensions.GroupOnlyValue">Только в группе</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn-gm btn-gm-primary" disabled="@IsBatchBusy(batch)">
|
||||
@(IsBatchBusy(batch) ? "⏳ Обновляем..." : "💾 Обновить title/link")
|
||||
@(IsBatchBusy(batch) ? "⏳ Обновляем..." : "💾 Обновить batch")
|
||||
</button>
|
||||
</EditForm>
|
||||
|
||||
@@ -115,7 +215,7 @@
|
||||
</div>
|
||||
|
||||
@* Desktop table *@
|
||||
<div class="glass-card session-table-desktop animate-slide-up" style="padding: 0; overflow: hidden;">
|
||||
<div class="glass-card session-table-desktop session-table-desktop-card animate-slide-up">
|
||||
<table class="gm-table">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -130,33 +230,81 @@
|
||||
<tbody>
|
||||
@foreach (var session in sessions)
|
||||
{
|
||||
var isExpanded = expandedSessions.Contains(session.Id);
|
||||
<tr>
|
||||
<td style="color: var(--text-primary); font-weight: 500;">@session.Title</td>
|
||||
<td style="color: var(--text-primary); font-weight: 500;">
|
||||
<button type="button" class="btn-gm btn-gm-link" @onclick="() => ToggleParticipants(session.Id)">
|
||||
@(isExpanded ? "▼" : "▶") @session.Title
|
||||
</button>
|
||||
</td>
|
||||
<td>@session.ScheduledAt.FormatMoscow()</td>
|
||||
<td>@FormatSeats(session)</td>
|
||||
<td>
|
||||
<span class="status-badge @GetStatusClass(session.Status)">@TranslateStatus(session.Status)</span>
|
||||
</td>
|
||||
<td>
|
||||
<a href="@session.JoinLink" target="_blank" rel="noopener noreferrer"
|
||||
style="max-width: 150px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
|
||||
<a href="@session.JoinLink" target="_blank" rel="noopener noreferrer" class="session-join-link">
|
||||
Подключиться ↗
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
|
||||
<a href="/session/edit/@session.Id" class="btn-gm btn-gm-outline" style="font-size: 0.8125rem; padding: 0.375rem 0.75rem;">
|
||||
<div class="session-table-actions">
|
||||
<a href="/session/edit/@session.Id" class="btn-gm btn-gm-outline">
|
||||
✏️ Изменить
|
||||
</a>
|
||||
<a href="/session/@session.Id/history" class="btn-gm btn-gm-outline">📜 История</a>
|
||||
@if (CanPromote(session))
|
||||
{
|
||||
<button type="button" class="btn-gm btn-gm-success" style="font-size: 0.8125rem; padding: 0.375rem 0.75rem;" disabled="@(promotingSessionId == session.Id)" @onclick="() => PromoteWaitlisted(session.Id)">
|
||||
<button type="button" class="btn-gm btn-gm-success" disabled="@(promotingSessionId == session.Id)" @onclick="() => PromoteWaitlisted(session.Id)">
|
||||
@(promotingSessionId == session.Id ? "⏳ Поднимаем..." : "⬆️ Из ожидания")
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@if (isExpanded)
|
||||
{
|
||||
<tr>
|
||||
<td colspan="6" style="padding: 0; border: none;">
|
||||
<div class="participant-panel">
|
||||
@if (loadingParticipantsSessionId == session.Id)
|
||||
{
|
||||
<div class="skeleton skeleton-text" style="width: 60%;"></div>
|
||||
}
|
||||
else if (participantsCache.TryGetValue(session.Id, out var participants))
|
||||
{
|
||||
@if (participants.Count == 0)
|
||||
{
|
||||
<div class="empty-state empty-state-compact">
|
||||
<div class="empty-state-title">Нет участников</div>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="participant-list">
|
||||
@foreach (var p in participants)
|
||||
{
|
||||
<div class="participant-row">
|
||||
<div class="participant-info">
|
||||
<span class="participant-name">@p.DisplayName</span>
|
||||
<span class="participant-username">@FormatParticipantUsername(p)</span>
|
||||
<span class="status-badge @GetParticipantStatusClass(p)">@TranslateParticipantStatus(p)</span>
|
||||
</div>
|
||||
@if (!p.IsGm)
|
||||
{
|
||||
<button type="button" class="btn-gm btn-gm-danger" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;" disabled="@(kickingParticipantId == p.Id)" @onclick="() => KickParticipant(session.Id, p.Id)">
|
||||
@(kickingParticipantId == p.Id ? "⏳..." : "🚪 Исключить")
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -166,9 +314,12 @@
|
||||
<div class="session-card-mobile stagger-children">
|
||||
@foreach (var session in sessions)
|
||||
{
|
||||
var isExpanded = expandedSessions.Contains(session.Id);
|
||||
<div class="session-card">
|
||||
<div class="session-card-header">
|
||||
<span class="session-card-title">@session.Title</span>
|
||||
<button type="button" class="btn-gm btn-gm-link" style="text-align: left; padding: 0;" @onclick="() => ToggleParticipants(session.Id)">
|
||||
@(isExpanded ? "▼" : "▶") @session.Title
|
||||
</button>
|
||||
<span class="status-badge @GetStatusClass(session.Status)">@TranslateStatus(session.Status)</span>
|
||||
</div>
|
||||
<div class="session-card-body">
|
||||
@@ -189,6 +340,7 @@
|
||||
<a href="/session/edit/@session.Id" class="btn-gm btn-gm-outline" style="flex: 1; justify-content: center; font-size: 0.8125rem; padding: 0.5rem;">
|
||||
✏️ Изменить
|
||||
</a>
|
||||
<a href="/session/@session.Id/history" class="btn-gm btn-gm-outline" style="flex: 1; justify-content: center; font-size: 0.8125rem; padding: 0.5rem;">📜 История</a>
|
||||
@if (CanPromote(session))
|
||||
{
|
||||
<button type="button" class="btn-gm btn-gm-success" style="flex: 1; justify-content: center; font-size: 0.8125rem; padding: 0.5rem;" disabled="@(promotingSessionId == session.Id)" @onclick="() => PromoteWaitlisted(session.Id)">
|
||||
@@ -196,6 +348,45 @@
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@if (isExpanded)
|
||||
{
|
||||
<div class="participant-panel" style="margin-top: 0.75rem;">
|
||||
@if (loadingParticipantsSessionId == session.Id)
|
||||
{
|
||||
<div class="skeleton skeleton-text" style="width: 60%;"></div>
|
||||
}
|
||||
else if (participantsCache.TryGetValue(session.Id, out var participants))
|
||||
{
|
||||
@if (participants.Count == 0)
|
||||
{
|
||||
<div class="empty-state empty-state-compact">
|
||||
<div class="empty-state-title">Нет участников</div>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="participant-list">
|
||||
@foreach (var p in participants)
|
||||
{
|
||||
<div class="participant-row">
|
||||
<div class="participant-info">
|
||||
<span class="participant-name">@p.DisplayName</span>
|
||||
<span class="participant-username">@FormatParticipantUsername(p)</span>
|
||||
<span class="status-badge @GetParticipantStatusClass(p)">@TranslateParticipantStatus(p)</span>
|
||||
</div>
|
||||
@if (!p.IsGm)
|
||||
{
|
||||
<button type="button" class="btn-gm btn-gm-danger" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;" disabled="@(kickingParticipantId == p.Id)" @onclick="() => KickParticipant(session.Id, p.Id)">
|
||||
@(kickingParticipantId == p.Id ? "⏳..." : "🚪 Исключить")
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -205,12 +396,23 @@
|
||||
@code {
|
||||
[Parameter] public Guid GroupId { get; set; }
|
||||
private List<WebSession>? sessions;
|
||||
private List<WebCampaignTemplate>? campaignTemplates;
|
||||
private WebGroupManagement? groupManagement;
|
||||
private List<BatchBulkEditModel> batchModels = [];
|
||||
private List<CampaignTemplateUsageModel> campaignTemplateModels = [];
|
||||
private Guid? promotingSessionId;
|
||||
private Guid? processingBatchId;
|
||||
private Guid? processingTemplateId;
|
||||
private long? removingCoGmId;
|
||||
private bool isAddingCoGm;
|
||||
private long telegramId;
|
||||
private string? errorMessage;
|
||||
private string? successMessage;
|
||||
private CoGmEditModel coGmModel = new();
|
||||
private Dictionary<Guid, List<WebParticipant>> participantsCache = new();
|
||||
private HashSet<Guid> expandedSessions = new();
|
||||
private Guid? kickingParticipantId;
|
||||
private Guid? loadingParticipantsSessionId;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
@@ -226,6 +428,13 @@
|
||||
|
||||
private async Task LoadSessions()
|
||||
{
|
||||
groupManagement = await SessionService.GetGroupManagementForGmAsync(GroupId, telegramId);
|
||||
if (groupManagement is null)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
|
||||
sessions = await SessionService.GetUpcomingSessionsForGmAsync(GroupId, telegramId);
|
||||
if (sessions is null)
|
||||
{
|
||||
@@ -233,7 +442,81 @@
|
||||
return;
|
||||
}
|
||||
|
||||
campaignTemplates = await SessionService.GetCampaignTemplatesForGmAsync(GroupId, telegramId);
|
||||
if (campaignTemplates is null)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
|
||||
RebuildBatchModels();
|
||||
RebuildCampaignTemplateModels();
|
||||
}
|
||||
|
||||
private async Task AddCoGm()
|
||||
{
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
|
||||
if (!coGmModel.TelegramId.HasValue || coGmModel.TelegramId.Value <= 0)
|
||||
{
|
||||
errorMessage = "Telegram ID co-GM должен быть положительным числом.";
|
||||
return;
|
||||
}
|
||||
|
||||
isAddingCoGm = true;
|
||||
|
||||
try
|
||||
{
|
||||
await SessionService.AddCoGmForOwnerAsync(
|
||||
GroupId,
|
||||
telegramId,
|
||||
coGmModel.TelegramId.Value,
|
||||
coGmModel.DisplayName,
|
||||
coGmModel.TelegramUsername);
|
||||
|
||||
coGmModel = new();
|
||||
successMessage = "Co-GM добавлен.";
|
||||
await LoadSessions();
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = "Не удалось добавить co-GM: " + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
isAddingCoGm = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RemoveCoGm(long coGmTelegramId)
|
||||
{
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
removingCoGmId = coGmTelegramId;
|
||||
|
||||
try
|
||||
{
|
||||
await SessionService.RemoveCoGmForOwnerAsync(GroupId, telegramId, coGmTelegramId);
|
||||
successMessage = "Co-GM удалён.";
|
||||
await LoadSessions();
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = "Не удалось удалить co-GM: " + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
removingCoGmId = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PromoteWaitlisted(Guid sessionId)
|
||||
@@ -261,6 +544,105 @@
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleParticipants(Guid sessionId)
|
||||
{
|
||||
if (expandedSessions.Contains(sessionId))
|
||||
{
|
||||
expandedSessions.Remove(sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
expandedSessions.Add(sessionId);
|
||||
|
||||
if (!participantsCache.ContainsKey(sessionId))
|
||||
{
|
||||
loadingParticipantsSessionId = sessionId;
|
||||
try
|
||||
{
|
||||
var participants = await SessionService.GetSessionParticipantsForGmAsync(sessionId, telegramId);
|
||||
participantsCache[sessionId] = participants ?? [];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = "Не удалось загрузить участников: " + ex.Message;
|
||||
expandedSessions.Remove(sessionId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
loadingParticipantsSessionId = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task KickParticipant(Guid sessionId, Guid participantId)
|
||||
{
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
kickingParticipantId = participantId;
|
||||
|
||||
try
|
||||
{
|
||||
await SessionService.RemovePlayerFromSessionForGmAsync(sessionId, telegramId, participantId);
|
||||
participantsCache.Remove(sessionId);
|
||||
successMessage = "Игрок исключён.";
|
||||
await LoadSessions();
|
||||
if (expandedSessions.Contains(sessionId))
|
||||
{
|
||||
await ToggleParticipants(sessionId);
|
||||
}
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
kickingParticipantId = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatParticipantUsername(WebParticipant p)
|
||||
{
|
||||
var username = string.IsNullOrWhiteSpace(p.TelegramUsername)
|
||||
? p.TelegramId.ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
: "@" + p.TelegramUsername;
|
||||
return $"{username} · {FormatParticipantRsvp(p.RsvpStatus)}";
|
||||
}
|
||||
|
||||
private static string FormatParticipantRsvp(string rsvp) => rsvp switch
|
||||
{
|
||||
RsvpStatus.Pending => "⏳ не ответил",
|
||||
RsvpStatus.Confirmed => "✅ подтвердил",
|
||||
RsvpStatus.Declined => "❌ отказался",
|
||||
_ => rsvp
|
||||
};
|
||||
|
||||
private static string GetParticipantStatusClass(WebParticipant p)
|
||||
{
|
||||
if (p.IsGm) return "status-success";
|
||||
return p.RegistrationStatus switch
|
||||
{
|
||||
"Active" => "status-info",
|
||||
"Waitlisted" => "status-warning",
|
||||
_ => "status-neutral"
|
||||
};
|
||||
}
|
||||
|
||||
private static string TranslateParticipantStatus(WebParticipant p)
|
||||
{
|
||||
if (p.IsGm) return "ГМ";
|
||||
return p.RegistrationStatus switch
|
||||
{
|
||||
"Active" => "Основной состав",
|
||||
"Waitlisted" => "Ожидание",
|
||||
_ => p.RegistrationStatus
|
||||
};
|
||||
}
|
||||
|
||||
private async Task UpdateBatchDetails(BatchBulkEditModel batch)
|
||||
{
|
||||
errorMessage = null;
|
||||
@@ -277,7 +659,11 @@
|
||||
try
|
||||
{
|
||||
await SessionService.UpdateBatchDetailsForGmAsync(batch.BatchId, telegramId, batch.Title, batch.JoinLink);
|
||||
successMessage = "Общие title/link обновлены для всей пачки.";
|
||||
await SessionService.UpdateBatchNotificationModeForGmAsync(
|
||||
batch.BatchId,
|
||||
telegramId,
|
||||
SessionNotificationModeExtensions.FromDatabaseValue(batch.NotificationMode));
|
||||
successMessage = "Настройки batch обновлены.";
|
||||
await LoadSessions();
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
@@ -358,6 +744,39 @@
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CreateBatchFromTemplate(CampaignTemplateUsageModel template)
|
||||
{
|
||||
errorMessage = null;
|
||||
successMessage = null;
|
||||
processingTemplateId = template.Id;
|
||||
|
||||
try
|
||||
{
|
||||
var utcTime = new DateTimeOffset(template.FirstScheduledAtLocal, TimeSpan.FromHours(3)).ToUniversalTime().UtcDateTime;
|
||||
if (utcTime <= DateTime.UtcNow)
|
||||
{
|
||||
errorMessage = "Первая дата batch должна быть в будущем.";
|
||||
return;
|
||||
}
|
||||
|
||||
var createdBatch = await SessionService.CreateBatchFromCampaignTemplateForGmAsync(template.Id, telegramId, utcTime);
|
||||
successMessage = $"Batch создан из шаблона: {createdBatch.SessionCount} игр.";
|
||||
await LoadSessions();
|
||||
}
|
||||
catch (SessionAccessDeniedException)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = "Не удалось создать batch из шаблона: " + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
processingTemplateId = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void RebuildBatchModels()
|
||||
{
|
||||
batchModels = sessions?
|
||||
@@ -373,6 +792,7 @@
|
||||
BatchId = group.Key,
|
||||
Title = firstSession.Title,
|
||||
JoinLink = firstSession.JoinLink,
|
||||
NotificationMode = firstSession.NotificationMode,
|
||||
FirstScheduledAtLocal = firstSession.ScheduledAt.ToMoscow(),
|
||||
LastScheduledAtLocal = lastSession.ScheduledAt.ToMoscow(),
|
||||
IntervalDays = InferIntervalDays(orderedSessions),
|
||||
@@ -383,6 +803,27 @@
|
||||
.ToList() ?? [];
|
||||
}
|
||||
|
||||
private void RebuildCampaignTemplateModels()
|
||||
{
|
||||
var defaultStart = DateTime.UtcNow.AddDays(7).ToMoscow();
|
||||
campaignTemplateModels = campaignTemplates?
|
||||
.OrderByDescending(template => template.UpdatedAt)
|
||||
.ThenBy(template => template.Name)
|
||||
.Select(template => new CampaignTemplateUsageModel
|
||||
{
|
||||
Id = template.Id,
|
||||
Name = template.Name,
|
||||
Title = template.Title,
|
||||
JoinLink = template.JoinLink,
|
||||
SessionCount = template.SessionCount,
|
||||
IntervalDays = template.IntervalDays,
|
||||
MaxPlayers = template.MaxPlayers,
|
||||
NotificationMode = template.NotificationMode,
|
||||
FirstScheduledAtLocal = defaultStart
|
||||
})
|
||||
.ToList() ?? [];
|
||||
}
|
||||
|
||||
private static bool ValidateBatchDetails(BatchBulkEditModel batch)
|
||||
{
|
||||
batch.Title = batch.Title.Trim();
|
||||
@@ -392,6 +833,24 @@
|
||||
|
||||
private bool IsBatchBusy(BatchBulkEditModel batch) => processingBatchId == batch.BatchId;
|
||||
|
||||
private bool IsTemplateBusy(CampaignTemplateUsageModel template) => processingTemplateId == template.Id;
|
||||
|
||||
private string CurrentUserRole =>
|
||||
groupManagement?.Managers.FirstOrDefault(manager => manager.TelegramId == telegramId)?.Role
|
||||
?? GroupManagerRoleExtensions.CoGmValue;
|
||||
|
||||
private static string FormatRole(string role) =>
|
||||
GroupManagerRoleExtensions.FromDatabaseValue(role).ToDisplayName();
|
||||
|
||||
private static string FormatManager(WebGroupManager manager)
|
||||
{
|
||||
var username = string.IsNullOrWhiteSpace(manager.TelegramUsername)
|
||||
? manager.TelegramId.ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
: "@" + manager.TelegramUsername;
|
||||
|
||||
return $"{FormatRole(manager.Role)} · {manager.DisplayName} · {username}";
|
||||
}
|
||||
|
||||
private static int InferIntervalDays(IReadOnlyList<WebSession> orderedSessions)
|
||||
{
|
||||
if (orderedSessions.Count < 2)
|
||||
@@ -421,6 +880,22 @@
|
||||
private static string FormatBatchSummary(BatchBulkEditModel batch) =>
|
||||
$"{batch.SessionCount} игр · {FormatLocalMoscow(batch.FirstScheduledAtLocal)} — {FormatLocalMoscow(batch.LastScheduledAtLocal)}";
|
||||
|
||||
private static string FormatTemplateSummary(CampaignTemplateUsageModel template)
|
||||
{
|
||||
var seats = template.MaxPlayers.HasValue
|
||||
? $"{template.MaxPlayers.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)} мест"
|
||||
: "без лимита";
|
||||
|
||||
return $"{template.Title} · {template.SessionCount} игр · каждые {template.IntervalDays} дн. · {seats} · {FormatNotificationMode(template.NotificationMode)}";
|
||||
}
|
||||
|
||||
private static string FormatNotificationMode(string notificationMode) =>
|
||||
SessionNotificationModeExtensions.FromDatabaseValue(notificationMode) switch
|
||||
{
|
||||
SessionNotificationMode.GroupOnly => "только группа",
|
||||
_ => "группа и личка"
|
||||
};
|
||||
|
||||
private static string FormatLocalMoscow(DateTime localMoscow) =>
|
||||
localMoscow.ToString("d MMMM yyyy, HH:mm", System.Globalization.CultureInfo.GetCultureInfo("ru-RU"));
|
||||
|
||||
@@ -447,10 +922,31 @@
|
||||
public Guid BatchId { get; init; }
|
||||
public string Title { get; set; } = "";
|
||||
public string JoinLink { get; set; } = "";
|
||||
public string NotificationMode { get; set; } = SessionNotificationModeExtensions.GroupAndDirectValue;
|
||||
public DateTime FirstScheduledAtLocal { get; set; } = DateTime.Now;
|
||||
public DateTime LastScheduledAtLocal { get; init; } = DateTime.Now;
|
||||
public int IntervalDays { get; set; } = 7;
|
||||
public int SessionCount { get; init; }
|
||||
public string CloneInterval { get; set; } = "week";
|
||||
}
|
||||
|
||||
private sealed class CampaignTemplateUsageModel
|
||||
{
|
||||
public Guid Id { get; init; }
|
||||
public string Name { get; init; } = "";
|
||||
public string Title { get; init; } = "";
|
||||
public string JoinLink { get; init; } = "";
|
||||
public int SessionCount { get; init; }
|
||||
public int IntervalDays { get; init; }
|
||||
public int? MaxPlayers { get; init; }
|
||||
public string NotificationMode { get; init; } = SessionNotificationModeExtensions.GroupAndDirectValue;
|
||||
public DateTime FirstScheduledAtLocal { get; set; } = DateTime.Now;
|
||||
}
|
||||
|
||||
private sealed class CoGmEditModel
|
||||
{
|
||||
public long? TelegramId { get; set; }
|
||||
public string DisplayName { get; set; } = "";
|
||||
public string? TelegramUsername { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
@page "/group/{GroupId:guid}/stats"
|
||||
@using GmRelay.Web.Services
|
||||
@using GmRelay.Shared.Domain
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using System.Security.Claims
|
||||
@attribute [Authorize]
|
||||
@inject ISessionStore SessionStore
|
||||
@inject AuthenticationStateProvider AuthStateProvider
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Статистика — GM-Relay</PageTitle>
|
||||
|
||||
<div class="page-container">
|
||||
<ul class="gm-breadcrumb animate-fade-in">
|
||||
<li><a href="/">Главная</a></li>
|
||||
<li><a href="/group/@GroupId">Сессии группы</a></li>
|
||||
<li class="active">Статистика</li>
|
||||
</ul>
|
||||
|
||||
<div class="page-header animate-fade-in">
|
||||
<h2>📊 Статистика посещаемости</h2>
|
||||
<p class="page-subtitle">Надёжность состава и качество расписания</p>
|
||||
</div>
|
||||
|
||||
@if (!string.IsNullOrEmpty(errorMessage))
|
||||
{
|
||||
<div class="gm-alert gm-alert-danger" style="margin-bottom: 1rem;">
|
||||
⚠️ @errorMessage
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (stats is null)
|
||||
{
|
||||
<div class="loading-spinner">⏳ Загружаем статистику…</div>
|
||||
}
|
||||
else if (stats.Count == 0)
|
||||
{
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">📈</div>
|
||||
<h3>Пока нет данных</h3>
|
||||
<p>После первых сессий здесь появится аналитика.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="glass-card animate-slide-up" style="margin-bottom: 1rem;">
|
||||
<div class="stats-summary" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">@stats.Count</div>
|
||||
<div class="stat-label">Игроков</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">@TotalSessions</div>
|
||||
<div class="stat-label">Сессий</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">@AvgAttendanceRate%</div>
|
||||
<div class="stat-label">Средняя посещаемость</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">@topPlayer?.DisplayName</div>
|
||||
<div class="stat-label">Самый стабильный</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="gm-table" style="width: 100%;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th @onclick="@(() => SortBy("player"))" style="cursor:pointer;" class="sortable">Игрок @(sortColumn == "player" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("total"))" style="cursor:pointer; text-align:center;" class="sortable">Всего @(sortColumn == "total" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("confirmed"))" style="cursor:pointer; text-align:center;" class="sortable">✅ @(sortColumn == "confirmed" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("declined"))" style="cursor:pointer; text-align:center;" class="sortable">❌ @(sortColumn == "declined" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("noresponse"))" style="cursor:pointer; text-align:center;" class="sortable">💤 @(sortColumn == "noresponse" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("waitlist"))" style="cursor:pointer; text-align:center;" class="sortable">⏳ @(sortColumn == "waitlist" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("rate"))" style="cursor:pointer; text-align:center;" class="sortable">% @(sortColumn == "rate" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
<th @onclick="@(() => SortBy("cancelled"))" style="cursor:pointer; text-align:center;" class="sortable">🚫 @(sortColumn == "cancelled" ? (sortDesc ? "▼" : "▲") : "")</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var s in sortedStats)
|
||||
{
|
||||
<tr>
|
||||
<td>
|
||||
<div class="player-info">
|
||||
<span class="player-name">@s.DisplayName</span>
|
||||
@if (!string.IsNullOrEmpty(s.TelegramUsername))
|
||||
{
|
||||
<span class="player-username">@@@s.TelegramUsername</span>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
<td style="text-align:center;">@s.TotalSessions</td>
|
||||
<td style="text-align:center;">@s.ConfirmedCount</td>
|
||||
<td style="text-align:center;">@s.DeclinedCount</td>
|
||||
<td style="text-align:center;">@s.NoResponseCount</td>
|
||||
<td style="text-align:center;">@s.WaitlistedCount</td>
|
||||
<td style="text-align:center;">
|
||||
<span class="rate-badge @AttendanceBadgeClass(s.AttendanceRate)">
|
||||
@s.AttendanceRate%
|
||||
</span>
|
||||
</td>
|
||||
<td style="text-align:center;">@s.CancellationAffectedCount</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.stat-card {
|
||||
background: var(--card-bg-secondary, rgba(255,255,255,0.05));
|
||||
border-radius: 0.75rem;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
.stat-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--accent-color, #7cb97a);
|
||||
}
|
||||
.stat-label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted, #94a3b8);
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.player-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.player-name {
|
||||
font-weight: 500;
|
||||
}
|
||||
.player-username {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted, #94a3b8);
|
||||
}
|
||||
.rate-badge {
|
||||
display: inline-block;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.5rem;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.rate-excellent { background: rgba(34,197,94,0.15); color: #22c55e; }
|
||||
.rate-good { background: rgba(234,179,8,0.15); color: #eab308; }
|
||||
.rate-poor { background: rgba(239,68,68,0.15); color: #ef4444; }
|
||||
</style>
|
||||
|
||||
@code {
|
||||
[Parameter] public Guid GroupId { get; set; }
|
||||
private List<PlayerAttendanceStats>? stats;
|
||||
private List<PlayerAttendanceStats> sortedStats = new();
|
||||
private string? errorMessage;
|
||||
private string sortColumn = "confirmed";
|
||||
private bool sortDesc = true;
|
||||
private int TotalSessions => stats?.Count > 0 ? (int)(stats.Max(s => s.TotalSessions)) : 0;
|
||||
private int AvgAttendanceRate => stats?.Count > 0 ? (int)(stats.Average(s => s.AttendanceRate)) : 0;
|
||||
private PlayerAttendanceStats? topPlayer => stats?.OrderByDescending(s => s.AttendanceRate).ThenByDescending(s => s.ConfirmedCount).FirstOrDefault();
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
|
||||
var user = authState.User;
|
||||
if (!user.Identity?.IsAuthenticated ?? true)
|
||||
{
|
||||
Navigation.NavigateTo("/login");
|
||||
return;
|
||||
}
|
||||
var telegramIdClaim = user.FindFirst("telegram_id")?.Value
|
||||
?? user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (!long.TryParse(telegramIdClaim, out var telegramId))
|
||||
{
|
||||
Navigation.NavigateTo("/login");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!await SessionStore.IsGroupManagerAsync(GroupId, telegramId))
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
stats = await SessionStore.GetGroupAttendanceStatsAsync(GroupId) ?? new();
|
||||
UpdateSortedStats();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errorMessage = $"Ошибка загрузки статистики: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void SortBy(string column)
|
||||
{
|
||||
if (sortColumn == column)
|
||||
sortDesc = !sortDesc;
|
||||
else
|
||||
{
|
||||
sortColumn = column;
|
||||
sortDesc = true;
|
||||
}
|
||||
UpdateSortedStats();
|
||||
}
|
||||
|
||||
private void UpdateSortedStats()
|
||||
{
|
||||
if (stats is null) { sortedStats = new(); return; }
|
||||
IOrderedEnumerable<PlayerAttendanceStats> ordered = sortColumn switch
|
||||
{
|
||||
"player" => sortDesc ? stats.OrderByDescending(s => s.DisplayName) : stats.OrderBy(s => s.DisplayName),
|
||||
"total" => sortDesc ? stats.OrderByDescending(s => s.TotalSessions) : stats.OrderBy(s => s.TotalSessions),
|
||||
"confirmed" => sortDesc ? stats.OrderByDescending(s => s.ConfirmedCount) : stats.OrderBy(s => s.ConfirmedCount),
|
||||
"declined" => sortDesc ? stats.OrderByDescending(s => s.DeclinedCount) : stats.OrderBy(s => s.DeclinedCount),
|
||||
"noresponse" => sortDesc ? stats.OrderByDescending(s => s.NoResponseCount) : stats.OrderBy(s => s.NoResponseCount),
|
||||
"waitlist" => sortDesc ? stats.OrderByDescending(s => s.WaitlistedCount) : stats.OrderBy(s => s.WaitlistedCount),
|
||||
"rate" => sortDesc ? stats.OrderByDescending(s => s.AttendanceRate) : stats.OrderBy(s => s.AttendanceRate),
|
||||
"cancelled" => sortDesc ? stats.OrderByDescending(s => s.CancellationAffectedCount) : stats.OrderBy(s => s.CancellationAffectedCount),
|
||||
_ => stats.OrderByDescending(s => s.ConfirmedCount)
|
||||
};
|
||||
sortedStats = ordered.ToList();
|
||||
}
|
||||
|
||||
private string SortIndicator(string column) => sortColumn == column ? (sortDesc ? "▼" : "▲") : "";
|
||||
|
||||
private string AttendanceBadgeClass(decimal rate) => rate switch
|
||||
{
|
||||
>= 75m => "rate-excellent",
|
||||
>= 50m => "rate-good",
|
||||
_ => "rate-poor"
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
@page "/"
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using GmRelay.Shared.Domain
|
||||
@using GmRelay.Web.Services
|
||||
@attribute [Authorize]
|
||||
@inject AuthorizedSessionService SessionService
|
||||
@@ -43,6 +44,9 @@
|
||||
<div class="group-card-icon">🎮</div>
|
||||
<h3 class="group-card-title">@group.Name</h3>
|
||||
<p class="group-card-id">ID: @group.TelegramChatId</p>
|
||||
<span class="status-badge @(group.ManagerRole == GroupManagerRoleExtensions.OwnerValue ? "status-success" : "status-info")" style="align-self: flex-start; margin-bottom: 1rem;">
|
||||
@FormatRole(group.ManagerRole)
|
||||
</span>
|
||||
<a href="/group/@group.Id" class="btn-gm btn-gm-primary" style="width: 100%; justify-content: center; margin-top: auto;">
|
||||
Посмотреть игры →
|
||||
</a>
|
||||
@@ -97,4 +101,7 @@
|
||||
|
||||
groups = await SessionService.GetGroupsForGmAsync(telegramId);
|
||||
}
|
||||
|
||||
private static string FormatRole(string role) =>
|
||||
GroupManagerRoleExtensions.FromDatabaseValue(role).ToDisplayName();
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
|
||||
@code {
|
||||
private string BotUsername => Configuration["Telegram:BotUsername"] ?? "GmRelayBot";
|
||||
private string AuthUrl => Navigation.ToAbsoluteUri("/auth/telegram").ToString();
|
||||
|
||||
[CascadingParameter]
|
||||
private Task<AuthenticationState>? AuthStateTask { get; set; }
|
||||
@@ -46,7 +45,8 @@
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
await JS.InvokeVoidAsync("loadTelegramWidget", BotUsername, AuthUrl);
|
||||
await JS.InvokeVoidAsync("loadTelegramWidget", BotUsername, "/auth/telegram-login");
|
||||
await JS.InvokeVoidAsync("watchTelegramMiniAppLogin", "/auth/status", "/", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
@page "/miniapp"
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using System.Text.Json.Serialization
|
||||
@inject IJSRuntime JS
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Mini App Dashboard — GM-Relay</PageTitle>
|
||||
|
||||
<div class="mini-app-page">
|
||||
<div class="mini-app-auth-card" data-auth-status="@miniAppAuthStatus">
|
||||
<div class="mini-app-logo">🎲</div>
|
||||
<h1>GM-Relay</h1>
|
||||
<p>@statusMessage</p>
|
||||
|
||||
@if (showFallback)
|
||||
{
|
||||
<a href="/login" class="btn-gm btn-gm-primary">Войти через Telegram</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private string statusMessage = "Открываем dashboard внутри Telegram...";
|
||||
private string miniAppAuthStatus = "starting";
|
||||
private bool showFallback;
|
||||
|
||||
[CascadingParameter]
|
||||
private Task<AuthenticationState>? AuthStateTask { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (AuthStateTask is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var user = (await AuthStateTask).User;
|
||||
if (user.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
Navigation.NavigateTo("/");
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (!firstRender)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var result = await JS.InvokeAsync<MiniAppAuthResult>(
|
||||
"authenticateTelegramMiniApp",
|
||||
"/auth/telegram-webapp",
|
||||
"/");
|
||||
|
||||
if (!result.Authenticated)
|
||||
{
|
||||
miniAppAuthStatus = string.IsNullOrWhiteSpace(result.Reason)
|
||||
? "telegram-auth-failed"
|
||||
: result.Reason;
|
||||
statusMessage = GetStatusMessage(miniAppAuthStatus);
|
||||
showFallback = true;
|
||||
StateHasChanged();
|
||||
await TryWatchLoginAsync();
|
||||
}
|
||||
}
|
||||
catch (JSException)
|
||||
{
|
||||
miniAppAuthStatus = "telegram-auth-failed";
|
||||
statusMessage = "Не удалось получить данные Telegram Mini App. Попробуйте открыть dashboard из бота.";
|
||||
showFallback = true;
|
||||
StateHasChanged();
|
||||
await TryWatchLoginAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryWatchLoginAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await JS.InvokeVoidAsync("watchTelegramMiniAppLogin", "/auth/status", "/");
|
||||
}
|
||||
catch (JSException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetStatusMessage(string reason) => reason switch
|
||||
{
|
||||
"telegram-webapp-missing" => "Mini App API не найден. Если страница открыта в браузере, войдите через Telegram.",
|
||||
"telegram-init-data-empty" => "Telegram открыл страницу без Mini App initData. Попробуйте войти через Telegram на этом экране.",
|
||||
"telegram-auth-failed" => "Не удалось проверить Telegram Mini App. Попробуйте войти через Telegram.",
|
||||
_ => "Mini App доступен из Telegram. Для браузера используйте обычный вход."
|
||||
};
|
||||
|
||||
private sealed record MiniAppAuthResult(
|
||||
[property: JsonPropertyName("authenticated")] bool Authenticated,
|
||||
[property: JsonPropertyName("reason")] string? Reason,
|
||||
[property: JsonPropertyName("status")] int? Status,
|
||||
[property: JsonPropertyName("redirectUrl")] string? RedirectUrl);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
@page "/session/{SessionId:guid}/history"
|
||||
@using GmRelay.Web.Services
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@attribute [Authorize]
|
||||
@inject AuthorizedSessionService SessionService
|
||||
@inject AuthenticationStateProvider AuthStateProvider
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>История изменений — GM-Relay</PageTitle>
|
||||
|
||||
<div class="page-container">
|
||||
<ul class="gm-breadcrumb animate-fade-in">
|
||||
<li><a href="/">Главная</a></li>
|
||||
<li><a href="/group/@groupId">Группа</a></li>
|
||||
<li class="active">История изменений</li>
|
||||
</ul>
|
||||
|
||||
<div class="page-header animate-fade-in">
|
||||
<h2>📜 История изменений</h2>
|
||||
@if (sessionTitle is not null)
|
||||
{
|
||||
<p style="color: var(--text-muted); margin-top: 0.25rem;">@sessionTitle</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (entries is null)
|
||||
{
|
||||
<div class="glass-card" style="padding: 2rem;">
|
||||
<div class="skeleton skeleton-text" style="width: 50%; margin-bottom: 1.5rem;"></div>
|
||||
<div class="skeleton skeleton-text" style="width: 100%; height: 2.5rem; margin-bottom: 1.5rem;"></div>
|
||||
</div>
|
||||
}
|
||||
else if (entries.Count == 0)
|
||||
{
|
||||
<div class="glass-card animate-slide-up" style="padding: 2rem; text-align: center;">
|
||||
<p style="color: var(--text-muted);">История изменений пуста. Значимые изменения (время, ссылка, название, участники) будут отображаться здесь.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="glass-card animate-slide-up">
|
||||
<div class="table-responsive">
|
||||
<table class="gm-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Время</th>
|
||||
<th>Актор</th>
|
||||
<th>Тип изменения</th>
|
||||
<th>Было</th>
|
||||
<th>Стало</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var entry in entries)
|
||||
{
|
||||
<tr>
|
||||
<td>@entry.ChangedAt.ToString("dd.MM.yyyy HH:mm") UTC</td>
|
||||
<td>@entry.ActorName (@entry.ActorTelegramId)</td>
|
||||
<td>
|
||||
<span class="status-badge @(GetBadgeClass(entry.ChangeType))">
|
||||
@GetChangeTypeLabel(entry.ChangeType)
|
||||
</span>
|
||||
</td>
|
||||
<td style="max-width: 200px; overflow-wrap: break-word; color: var(--text-muted);">@(entry.OldValue ?? "—")</td>
|
||||
<td style="max-width: 200px; overflow-wrap: break-word;">@(entry.NewValue ?? "—")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public Guid SessionId { get; set; }
|
||||
private List<SessionAuditLogEntry>? entries;
|
||||
private string? sessionTitle;
|
||||
private Guid? groupId;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
|
||||
if (!authState.User.TryGetTelegramId(out var telegramId))
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
|
||||
var session = await SessionService.GetSessionForGmAsync(SessionId, telegramId);
|
||||
if (session is null)
|
||||
{
|
||||
Navigation.NavigateTo("/access-denied");
|
||||
return;
|
||||
}
|
||||
|
||||
sessionTitle = session.Title;
|
||||
groupId = session.GroupId;
|
||||
entries = await SessionService.GetSessionHistoryForGmAsync(SessionId, telegramId);
|
||||
}
|
||||
|
||||
private string GetChangeTypeLabel(string changeType) => changeType switch
|
||||
{
|
||||
"Title" => "Название",
|
||||
"Time" => "Время",
|
||||
"Link" => "Ссылка",
|
||||
"MaxPlayers" => "Лимит мест",
|
||||
"Status" => "Статус",
|
||||
"WaitlistPromote" => "Продвижение из листа ожидания",
|
||||
"PlayerRemoved" => "Исключение игрока",
|
||||
"BatchRescheduled" => "Перенос батча",
|
||||
"Cancelled" => "Отмена",
|
||||
_ => changeType
|
||||
};
|
||||
|
||||
private string GetBadgeClass(string changeType) => changeType switch
|
||||
{
|
||||
"Cancelled" or "PlayerRemoved" => "status-danger",
|
||||
"WaitlistPromote" => "status-success",
|
||||
"BatchRescheduled" or "Time" => "status-warning",
|
||||
_ => "status-info"
|
||||
};
|
||||
}
|
||||
+79
-10
@@ -23,6 +23,7 @@ builder.AddNpgsqlDataSource("gmrelaydb");
|
||||
builder.Services.AddSingleton<TelegramAuthService>();
|
||||
builder.Services.AddSingleton<ISessionStore, SessionService>();
|
||||
builder.Services.AddScoped<AuthorizedSessionService>();
|
||||
builder.Services.AddScoped<CalendarSubscriptionService>();
|
||||
|
||||
// Add Bot Client
|
||||
builder.Services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
@@ -87,27 +88,95 @@ app.MapGet("/auth/telegram", async (HttpContext context, TelegramAuthService aut
|
||||
{
|
||||
if (authService.Verify(context.Request.Query, out var telegramId, out var name))
|
||||
{
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, telegramId.ToString()),
|
||||
new Claim(ClaimTypes.Name, name),
|
||||
new Claim("TelegramId", telegramId.ToString())
|
||||
};
|
||||
|
||||
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
var authProperties = new AuthenticationProperties { IsPersistent = true };
|
||||
|
||||
await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
|
||||
await context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
CreateTelegramPrincipal(telegramId, name),
|
||||
authProperties);
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
return Results.Redirect("/login?error=auth_failed");
|
||||
});
|
||||
|
||||
app.MapPost("/auth/telegram-webapp", async (
|
||||
HttpContext context,
|
||||
TelegramAuthService authService,
|
||||
TelegramWebAppAuthRequest request) =>
|
||||
{
|
||||
if (!authService.VerifyWebAppInitData(request.InitData, out var telegramId, out var name))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var authProperties = new AuthenticationProperties { IsPersistent = true };
|
||||
await context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
CreateTelegramPrincipal(telegramId, name),
|
||||
authProperties);
|
||||
|
||||
return Results.Ok(new { redirectUrl = "/" });
|
||||
}).DisableAntiforgery();
|
||||
|
||||
app.MapPost("/auth/telegram-login", async (
|
||||
HttpContext context,
|
||||
TelegramAuthService authService,
|
||||
TelegramLoginPayload request) =>
|
||||
{
|
||||
if (!authService.VerifyLoginPayload(request, out var telegramId, out var name))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var authProperties = new AuthenticationProperties { IsPersistent = true };
|
||||
await context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
CreateTelegramPrincipal(telegramId, name),
|
||||
authProperties);
|
||||
|
||||
return Results.Ok(new { redirectUrl = "/" });
|
||||
}).DisableAntiforgery();
|
||||
|
||||
app.MapGet("/auth/status", (HttpContext context) =>
|
||||
Results.Ok(new { authenticated = context.User.Identity?.IsAuthenticated == true }));
|
||||
|
||||
app.MapPost("/auth/logout", async (HttpContext context) =>
|
||||
{
|
||||
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return Results.Redirect("/");
|
||||
});
|
||||
|
||||
// Public calendar subscription endpoint (no auth required)
|
||||
app.MapGet("/calendar/{token}.ics", async (
|
||||
string token,
|
||||
CalendarSubscriptionService service,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var ics = await service.GetIcsAsync(token, ct);
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(ics);
|
||||
return Results.File(bytes, "text/calendar", "schedule.ics");
|
||||
}
|
||||
catch (SubscriptionNotFoundException)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
});
|
||||
|
||||
app.Run();
|
||||
|
||||
static ClaimsPrincipal CreateTelegramPrincipal(long telegramId, string name)
|
||||
{
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture)),
|
||||
new(ClaimTypes.Name, name),
|
||||
new("TelegramId", telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture))
|
||||
};
|
||||
|
||||
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return new ClaimsPrincipal(claimsIdentity);
|
||||
}
|
||||
|
||||
public sealed record TelegramWebAppAuthRequest(string InitData);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public sealed class AuthorizedSessionService(ISessionStore sessionStore)
|
||||
@@ -5,6 +7,24 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
|
||||
public Task<List<WebGameGroup>> GetGroupsForGmAsync(long gmId) =>
|
||||
sessionStore.GetGroupsForGmAsync(gmId);
|
||||
|
||||
public async Task<WebGroupManagement?> GetGroupManagementForGmAsync(Guid groupId, long gmId)
|
||||
{
|
||||
if (!await GroupBelongsToGmAsync(groupId, gmId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var group = await sessionStore.GetGroupAsync(groupId);
|
||||
if (group is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var managers = await sessionStore.GetGroupManagersAsync(groupId);
|
||||
var isOwner = await sessionStore.IsGroupOwnerAsync(groupId, gmId);
|
||||
return new WebGroupManagement(group, managers, isOwner);
|
||||
}
|
||||
|
||||
public async Task<List<WebSession>?> GetUpcomingSessionsForGmAsync(Guid groupId, long gmId)
|
||||
{
|
||||
if (!await GroupBelongsToGmAsync(groupId, gmId))
|
||||
@@ -46,6 +66,15 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
|
||||
}
|
||||
|
||||
await sessionStore.UpdateSessionAsync(sessionId, session.GroupId, title, scheduledAt, joinLink, maxPlayers);
|
||||
|
||||
if (session.Title != title)
|
||||
await sessionStore.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Title", session.Title, title);
|
||||
if (session.ScheduledAt != scheduledAt)
|
||||
await sessionStore.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Time", session.ScheduledAt.ToString("O"), scheduledAt.ToString("O"));
|
||||
if (session.JoinLink != joinLink)
|
||||
await sessionStore.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Link", session.JoinLink, joinLink);
|
||||
if (session.MaxPlayers != maxPlayers)
|
||||
await sessionStore.LogSessionChangeAsync(sessionId, gmId, "ГМ", "MaxPlayers", session.MaxPlayers?.ToString(), maxPlayers?.ToString());
|
||||
}
|
||||
|
||||
public async Task PromoteWaitlistedPlayerForGmAsync(Guid sessionId, long gmId)
|
||||
@@ -57,6 +86,7 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
|
||||
}
|
||||
|
||||
await sessionStore.PromoteWaitlistedPlayerAsync(sessionId, session.GroupId);
|
||||
await sessionStore.LogSessionChangeAsync(sessionId, gmId, "ГМ", "WaitlistPromote", null, null);
|
||||
}
|
||||
|
||||
public async Task UpdateBatchDetailsForGmAsync(Guid batchId, long gmId, string title, string joinLink)
|
||||
@@ -70,6 +100,17 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
|
||||
await sessionStore.UpdateBatchDetailsAsync(batchId, batch.GroupId, title.Trim(), joinLink.Trim());
|
||||
}
|
||||
|
||||
public async Task UpdateBatchNotificationModeForGmAsync(Guid batchId, long gmId, SessionNotificationMode notificationMode)
|
||||
{
|
||||
var batch = await GetBatchForGmAsync(batchId, gmId);
|
||||
if (batch is null)
|
||||
{
|
||||
throw new SessionAccessDeniedException(batchId, gmId);
|
||||
}
|
||||
|
||||
await sessionStore.UpdateBatchNotificationModeAsync(batchId, batch.GroupId, notificationMode);
|
||||
}
|
||||
|
||||
public async Task RescheduleBatchForGmAsync(Guid batchId, long gmId, DateTime firstScheduledAt, int intervalDays)
|
||||
{
|
||||
if (intervalDays <= 0)
|
||||
@@ -84,6 +125,7 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
|
||||
}
|
||||
|
||||
await sessionStore.RescheduleBatchAsync(batchId, batch.GroupId, firstScheduledAt, intervalDays);
|
||||
await sessionStore.LogSessionChangeAsync(batchId, gmId, "ГМ", "BatchRescheduled", batch.FirstScheduledAt.ToString("O"), firstScheduledAt.ToString("O"));
|
||||
}
|
||||
|
||||
public async Task<WebSessionBatch> CloneBatchForGmAsync(Guid batchId, long gmId, BatchCloneInterval interval)
|
||||
@@ -97,9 +139,177 @@ 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)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(coGmTelegramId), coGmTelegramId, "Telegram id must be greater than zero.");
|
||||
}
|
||||
|
||||
if (ownerTelegramId == coGmTelegramId)
|
||||
{
|
||||
throw new InvalidOperationException("Owner is already a group manager.");
|
||||
}
|
||||
|
||||
if (!await sessionStore.IsGroupOwnerAsync(groupId, ownerTelegramId))
|
||||
{
|
||||
throw new SessionAccessDeniedException(groupId, ownerTelegramId);
|
||||
}
|
||||
|
||||
var normalizedName = string.IsNullOrWhiteSpace(displayName)
|
||||
? $"Telegram {coGmTelegramId.ToString(System.Globalization.CultureInfo.InvariantCulture)}"
|
||||
: displayName.Trim();
|
||||
var normalizedUsername = string.IsNullOrWhiteSpace(telegramUsername)
|
||||
? null
|
||||
: telegramUsername.Trim().TrimStart('@');
|
||||
|
||||
await sessionStore.AddGroupCoGmAsync(groupId, ownerTelegramId, coGmTelegramId, normalizedName, normalizedUsername);
|
||||
}
|
||||
|
||||
public async Task RemoveCoGmForOwnerAsync(Guid groupId, long ownerTelegramId, long coGmTelegramId)
|
||||
{
|
||||
if (!await sessionStore.IsGroupOwnerAsync(groupId, ownerTelegramId))
|
||||
{
|
||||
throw new SessionAccessDeniedException(groupId, ownerTelegramId);
|
||||
}
|
||||
|
||||
await sessionStore.RemoveGroupCoGmAsync(groupId, coGmTelegramId);
|
||||
}
|
||||
|
||||
public async Task<List<WebParticipant>?> GetSessionParticipantsForGmAsync(Guid sessionId, long gmId)
|
||||
{
|
||||
var session = await GetSessionForGmAsync(sessionId, gmId);
|
||||
if (session is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return await sessionStore.GetSessionParticipantsAsync(sessionId);
|
||||
}
|
||||
|
||||
public async Task<List<SessionAuditLogEntry>?> GetSessionHistoryForGmAsync(Guid sessionId, long gmId)
|
||||
{
|
||||
var session = await GetSessionForGmAsync(sessionId, gmId);
|
||||
if (session is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return await sessionStore.GetSessionHistoryAsync(sessionId);
|
||||
}
|
||||
|
||||
public async Task RemovePlayerFromSessionForGmAsync(Guid sessionId, long gmId, Guid participantId)
|
||||
{
|
||||
var session = await GetSessionForGmAsync(sessionId, gmId);
|
||||
if (session is null)
|
||||
{
|
||||
throw new SessionAccessDeniedException(sessionId, gmId);
|
||||
}
|
||||
|
||||
await sessionStore.RemovePlayerFromSessionAsync(sessionId, session.GroupId, participantId);
|
||||
await sessionStore.LogSessionChangeAsync(sessionId, gmId, "ГМ", "PlayerRemoved", participantId.ToString(), null);
|
||||
}
|
||||
|
||||
private async Task<bool> GroupBelongsToGmAsync(Guid groupId, long gmId)
|
||||
{
|
||||
var group = await sessionStore.GetGroupAsync(groupId);
|
||||
return group?.GmTelegramId == gmId;
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Handles editing batch messages that may be either text or photo messages.
|
||||
/// When the batch was created with SendPhoto (image + caption), we need
|
||||
/// EditMessageCaption instead of EditMessageText.
|
||||
/// </summary>
|
||||
public static class BatchMessageEditor
|
||||
{
|
||||
/// <summary>
|
||||
/// Edits a batch message, automatically detecting whether it is a text or photo message.
|
||||
/// Tries EditMessageText first; on failure falls back to EditMessageCaption.
|
||||
/// </summary>
|
||||
public static async Task EditBatchMessageAsync(
|
||||
ITelegramBotClient bot,
|
||||
long chatId,
|
||||
int messageId,
|
||||
string text,
|
||||
InlineKeyboardMarkup? replyMarkup,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await bot.EditMessageText(
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
text: text,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: replyMarkup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Telegram.Bot.Exceptions.ApiRequestException ex)
|
||||
when (ex.Message.Contains("there is no text in the message", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// The batch message is a photo — use EditMessageCaption instead.
|
||||
// Caption is limited to 1024 chars; if text exceeds that, truncate gracefully.
|
||||
var caption = text.Length <= 1024 ? text : text[..1021] + "...";
|
||||
await bot.EditMessageCaption(
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
caption: caption,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: replyMarkup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public enum BatchCloneInterval
|
||||
@@ -13,10 +15,36 @@ public sealed record WebSessionBatch(
|
||||
string JoinLink,
|
||||
DateTime FirstScheduledAt,
|
||||
DateTime LastScheduledAt,
|
||||
int SessionCount);
|
||||
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,
|
||||
@@ -33,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
|
||||
{
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public sealed class CalendarSubscriptionService(NpgsqlDataSource dataSource)
|
||||
{
|
||||
private const string IcsProdId = "-//GM-Relay//TTRPG Schedule//EN";
|
||||
|
||||
public string GenerateToken() => Guid.NewGuid().ToString("N");
|
||||
|
||||
public async Task<string> CreateSubscriptionAsync(
|
||||
long userTelegramId,
|
||||
Guid? groupId,
|
||||
CalendarSubscriptionFilter filter,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var token = GenerateToken();
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
await connection.ExecuteAsync(
|
||||
@"INSERT INTO calendar_subscriptions (id, token, user_telegram_id, group_id, filter_type, created_at, expires_at)
|
||||
VALUES (gen_random_uuid(), @token, @userTelegramId, @groupId, @filterType, now(), NULL)",
|
||||
new { token, userTelegramId, groupId, filterType = (int)filter });
|
||||
return token;
|
||||
}
|
||||
|
||||
public async Task<string> GetIcsAsync(string token, CancellationToken ct = default)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(ct);
|
||||
|
||||
var subscription = await connection.QueryFirstOrDefaultAsync<SubscriptionRecord>(
|
||||
@"SELECT id, user_telegram_id as UserTelegramId, group_id as GroupId, filter_type as FilterType
|
||||
FROM calendar_subscriptions
|
||||
WHERE token = @token
|
||||
AND (expires_at IS NULL OR expires_at > now())",
|
||||
new { token });
|
||||
|
||||
if (subscription is null)
|
||||
throw new SubscriptionNotFoundException();
|
||||
|
||||
var sessions = await connection.QueryAsync<CalendarSessionDto>(
|
||||
subscription.FilterType == (int)CalendarSubscriptionFilter.SpecificGroup && subscription.GroupId.HasValue
|
||||
? @"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt
|
||||
FROM sessions s
|
||||
WHERE s.group_id = @GroupId
|
||||
AND s.status = @Planned
|
||||
AND s.scheduled_at > NOW()
|
||||
ORDER BY s.scheduled_at ASC"
|
||||
: @"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt
|
||||
FROM sessions s
|
||||
WHERE s.status = @Planned
|
||||
AND s.scheduled_at > NOW()
|
||||
ORDER BY s.scheduled_at ASC",
|
||||
new { subscription.GroupId, Planned = SessionStatus.Planned });
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("BEGIN:VCALENDAR");
|
||||
sb.AppendLine("VERSION:2.0");
|
||||
sb.AppendLine($"PRODID:{IcsProdId}");
|
||||
sb.AppendLine("CALSCALE:GREGORIAN");
|
||||
sb.AppendLine("METHOD:PUBLISH");
|
||||
|
||||
foreach (var s in sessions)
|
||||
{
|
||||
var dtStart = FormatIcsDate(s.ScheduledAt);
|
||||
var dtEnd = FormatIcsDate(s.ScheduledAt.AddHours(4));
|
||||
sb.AppendLine("BEGIN:VEVENT");
|
||||
sb.AppendLine($"UID:{s.Id}@gmrelay");
|
||||
sb.AppendLine($"DTSTAMP:{FormatIcsDate(DateTime.UtcNow)}");
|
||||
sb.AppendLine($"DTSTART:{dtStart}");
|
||||
sb.AppendLine($"DTEND:{dtEnd}");
|
||||
sb.AppendLine($"SUMMARY:{EscapeIcsText(s.Title)}");
|
||||
sb.AppendLine("END:VEVENT");
|
||||
}
|
||||
|
||||
sb.AppendLine("END:VCALENDAR");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string FormatIcsDate(DateTime dt) => dt.ToUniversalTime().ToString("yyyyMMddTHHmmssZ");
|
||||
|
||||
private static string EscapeIcsText(string text) => text
|
||||
.Replace("\\", "\\\\")
|
||||
.Replace(";", "\\;")
|
||||
.Replace(",", "\\,")
|
||||
.Replace("\n", "\\n")
|
||||
.Replace("\r", "");
|
||||
|
||||
private sealed record SubscriptionRecord(Guid Id, long UserTelegramId, Guid? GroupId, int FilterType);
|
||||
private sealed record CalendarSessionDto(Guid Id, string Title, DateTime ScheduledAt);
|
||||
}
|
||||
@@ -1,15 +1,57 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public sealed record PlayerAttendanceStats(
|
||||
Guid PlayerId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
long TotalSessions,
|
||||
long ConfirmedCount,
|
||||
long DeclinedCount,
|
||||
long NoResponseCount,
|
||||
long WaitlistedCount,
|
||||
long CancellationAffectedCount,
|
||||
decimal AttendanceRate
|
||||
);
|
||||
|
||||
public sealed record SessionAuditLogEntry(
|
||||
Guid Id,
|
||||
Guid SessionId,
|
||||
long ActorTelegramId,
|
||||
string ActorName,
|
||||
string ChangeType,
|
||||
string? OldValue,
|
||||
string? NewValue,
|
||||
DateTime ChangedAt
|
||||
);
|
||||
|
||||
public interface ISessionStore
|
||||
{
|
||||
Task<List<WebGameGroup>> GetGroupsForGmAsync(long gmId);
|
||||
Task<WebGameGroup?> GetGroupAsync(Guid groupId);
|
||||
Task<bool> IsGroupManagerAsync(Guid groupId, long telegramId);
|
||||
Task<bool> IsGroupOwnerAsync(Guid groupId, long telegramId);
|
||||
Task<List<WebGroupManager>> GetGroupManagersAsync(Guid groupId);
|
||||
Task<List<WebSession>> GetUpcomingSessionsAsync(Guid groupId);
|
||||
Task<WebSession?> GetSessionAsync(Guid sessionId);
|
||||
Task<WebSessionBatch?> GetBatchAsync(Guid batchId);
|
||||
Task UpdateSessionAsync(Guid sessionId, Guid groupId, string title, DateTime scheduledAt, string joinLink, int? maxPlayers);
|
||||
Task PromoteWaitlistedPlayerAsync(Guid sessionId, Guid groupId);
|
||||
Task UpdateBatchDetailsAsync(Guid batchId, Guid groupId, string title, string joinLink);
|
||||
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);
|
||||
Task<List<WebParticipant>> GetSessionParticipantsAsync(Guid sessionId);
|
||||
Task RemovePlayerFromSessionAsync(Guid sessionId, Guid groupId, Guid participantId);
|
||||
Task<List<PlayerAttendanceStats>> GetGroupAttendanceStatsAsync(Guid groupId);
|
||||
Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue);
|
||||
Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,28 @@ using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using GmRelay.Web.Services;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public sealed record WebGameGroup(Guid Id, long TelegramChatId, string Name, long GmTelegramId);
|
||||
public sealed record WebGameGroup(
|
||||
Guid Id,
|
||||
long TelegramChatId,
|
||||
string Name,
|
||||
long GmTelegramId,
|
||||
string ManagerRole = GroupManagerRoleExtensions.OwnerValue);
|
||||
|
||||
public sealed record WebGroupManager(
|
||||
long TelegramId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
string Role,
|
||||
DateTime AddedAt);
|
||||
|
||||
public sealed record WebGroupManagement(
|
||||
WebGameGroup Group,
|
||||
IReadOnlyList<WebGroupManager> Managers,
|
||||
bool CurrentUserIsOwner);
|
||||
public sealed record WebSession(
|
||||
Guid Id,
|
||||
Guid GroupId,
|
||||
@@ -19,9 +37,21 @@ public sealed record WebSession(
|
||||
long TelegramChatId,
|
||||
int? MaxPlayers,
|
||||
int ActivePlayerCount,
|
||||
int WaitlistedPlayerCount);
|
||||
int WaitlistedPlayerCount,
|
||||
string NotificationMode = SessionNotificationModeExtensions.GroupAndDirectValue);
|
||||
|
||||
public sealed record WebParticipant(
|
||||
Guid Id,
|
||||
long TelegramId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
string RsvpStatus,
|
||||
string RegistrationStatus,
|
||||
bool IsGm,
|
||||
DateTime? RespondedAt);
|
||||
|
||||
internal sealed record WebPromotedParticipantDto(Guid ParticipantRowId, string DisplayName);
|
||||
internal sealed record WebDirectNotificationRecipient(long TelegramId, string DisplayName);
|
||||
internal sealed record WebBatchInfo(
|
||||
Guid BatchId,
|
||||
Guid GroupId,
|
||||
@@ -29,7 +59,8 @@ internal sealed record WebBatchInfo(
|
||||
string JoinLink,
|
||||
long TelegramChatId,
|
||||
int? BatchMessageId,
|
||||
int? ThreadId);
|
||||
int? ThreadId,
|
||||
string NotificationMode);
|
||||
|
||||
internal sealed record WebBatchSessionRow(
|
||||
Guid Id,
|
||||
@@ -41,7 +72,9 @@ internal sealed record WebBatchSessionRow(
|
||||
int? MaxPlayers,
|
||||
int? BatchMessageId,
|
||||
long TelegramChatId,
|
||||
int? ThreadId);
|
||||
int? ThreadId,
|
||||
string NotificationMode);
|
||||
internal sealed record WebTemplateGroupDto(long TelegramChatId);
|
||||
|
||||
public sealed class SessionService(
|
||||
NpgsqlDataSource dataSource,
|
||||
@@ -52,7 +85,18 @@ public sealed class SessionService(
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return (await conn.QueryAsync<WebGameGroup>(
|
||||
"SELECT id, telegram_chat_id AS TelegramChatId, name, gm_telegram_id AS GmTelegramId FROM game_groups WHERE gm_telegram_id = @GmId",
|
||||
"""
|
||||
SELECT g.id,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
g.name,
|
||||
g.gm_telegram_id AS GmTelegramId,
|
||||
gm.role AS ManagerRole
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
JOIN game_groups g ON g.id = gm.group_id
|
||||
WHERE p.telegram_id = @GmId
|
||||
ORDER BY g.name
|
||||
""",
|
||||
new { GmId = gmId })).ToList();
|
||||
}
|
||||
|
||||
@@ -60,8 +104,204 @@ public sealed class SessionService(
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return await conn.QuerySingleOrDefaultAsync<WebGameGroup>(
|
||||
"SELECT id, telegram_chat_id AS TelegramChatId, name, gm_telegram_id AS GmTelegramId FROM game_groups WHERE id = @GroupId",
|
||||
new { GroupId = groupId });
|
||||
"""
|
||||
SELECT g.id,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
g.name,
|
||||
g.gm_telegram_id AS GmTelegramId,
|
||||
@OwnerRole AS ManagerRole
|
||||
FROM game_groups g
|
||||
WHERE g.id = @GroupId
|
||||
""",
|
||||
new { GroupId = groupId, OwnerRole = GroupManagerRoleExtensions.OwnerValue });
|
||||
}
|
||||
|
||||
public async Task<bool> IsGroupManagerAsync(Guid groupId, long telegramId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return await conn.ExecuteScalarAsync<bool>(
|
||||
"""
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = @GroupId
|
||||
AND p.telegram_id = @TelegramId
|
||||
)
|
||||
""",
|
||||
new { GroupId = groupId, TelegramId = telegramId });
|
||||
}
|
||||
|
||||
public async Task<bool> IsGroupOwnerAsync(Guid groupId, long telegramId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return await conn.ExecuteScalarAsync<bool>(
|
||||
"""
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = @GroupId
|
||||
AND p.telegram_id = @TelegramId
|
||||
AND gm.role = @OwnerRole
|
||||
)
|
||||
""",
|
||||
new { GroupId = groupId, TelegramId = telegramId, OwnerRole = GroupManagerRoleExtensions.OwnerValue });
|
||||
}
|
||||
|
||||
public async Task<List<WebGroupManager>> GetGroupManagersAsync(Guid groupId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return (await conn.QueryAsync<WebGroupManager>(
|
||||
"""
|
||||
SELECT p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
gm.role AS Role,
|
||||
gm.created_at AS AddedAt
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = @GroupId
|
||||
ORDER BY CASE gm.role WHEN @OwnerRole THEN 0 ELSE 1 END,
|
||||
gm.created_at,
|
||||
p.display_name
|
||||
""",
|
||||
new { GroupId = groupId, OwnerRole = GroupManagerRoleExtensions.OwnerValue })).ToList();
|
||||
}
|
||||
|
||||
public async Task<List<PlayerAttendanceStats>> GetGroupAttendanceStatsAsync(Guid groupId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return (await conn.QueryAsync<PlayerAttendanceStats>(
|
||||
"""
|
||||
SELECT
|
||||
p.id AS PlayerId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
COUNT(DISTINCT s.id) AS TotalSessions,
|
||||
COUNT(DISTINCT CASE WHEN sp.rsvp_status = 'Confirmed' THEN s.id END) AS ConfirmedCount,
|
||||
COUNT(DISTINCT CASE WHEN sp.rsvp_status = 'Declined' THEN s.id END) AS DeclinedCount,
|
||||
COUNT(DISTINCT CASE WHEN sp.rsvp_status = 'Pending' THEN s.id END) AS NoResponseCount,
|
||||
COUNT(DISTINCT CASE WHEN sp.registration_status = 'Waitlisted' THEN s.id END) AS WaitlistedCount,
|
||||
COUNT(DISTINCT CASE WHEN s.status = 'Cancelled' AND sp.rsvp_status IN ('Confirmed','Declined') THEN s.id END) AS CancellationAffectedCount,
|
||||
CASE WHEN COUNT(DISTINCT s.id) > 0
|
||||
THEN ROUND(
|
||||
COUNT(DISTINCT CASE WHEN sp.rsvp_status = 'Confirmed' THEN s.id END)
|
||||
* 100.0 / COUNT(DISTINCT s.id), 2)
|
||||
ELSE 0
|
||||
END AS AttendanceRate
|
||||
FROM players p
|
||||
JOIN session_participants sp ON sp.player_id = p.id
|
||||
JOIN sessions s ON s.id = sp.session_id
|
||||
WHERE s.group_id = @GroupId
|
||||
AND s.scheduled_at <= now()
|
||||
AND sp.is_gm = false
|
||||
GROUP BY p.id, p.display_name, p.telegram_username
|
||||
ORDER BY AttendanceRate DESC, ConfirmedCount DESC
|
||||
""",
|
||||
new { GroupId = groupId })).ToList();
|
||||
}
|
||||
|
||||
public async Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO session_audit_log (session_id, actor_telegram_id, actor_name, change_type, old_value, new_value)
|
||||
VALUES (@SessionId, @ActorTelegramId, @ActorName, @ChangeType, @OldValue, @NewValue)
|
||||
""",
|
||||
new { SessionId = sessionId, ActorTelegramId = actorTelegramId, ActorName = actorName, ChangeType = changeType, OldValue = oldValue, NewValue = newValue });
|
||||
}
|
||||
|
||||
public async Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
var entries = await conn.QueryAsync<SessionAuditLogEntry>(
|
||||
"""
|
||||
SELECT id, session_id AS SessionId, actor_telegram_id AS ActorTelegramId, actor_name AS ActorName,
|
||||
change_type AS ChangeType, old_value AS OldValue, new_value AS NewValue, changed_at AS ChangedAt
|
||||
FROM session_audit_log
|
||||
WHERE session_id = @SessionId
|
||||
ORDER BY changed_at DESC
|
||||
""",
|
||||
new { SessionId = sessionId });
|
||||
return entries.ToList();
|
||||
}
|
||||
|
||||
public async Task AddGroupCoGmAsync(
|
||||
Guid groupId,
|
||||
long ownerTelegramId,
|
||||
long coGmTelegramId,
|
||||
string displayName,
|
||||
string? telegramUsername)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
await using var transaction = await conn.BeginTransactionAsync();
|
||||
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO players (telegram_id, display_name, telegram_username)
|
||||
VALUES (@TelegramId, @DisplayName, @TelegramUsername)
|
||||
ON CONFLICT (telegram_id) DO UPDATE
|
||||
SET display_name = EXCLUDED.display_name,
|
||||
telegram_username = EXCLUDED.telegram_username
|
||||
""",
|
||||
new
|
||||
{
|
||||
TelegramId = coGmTelegramId,
|
||||
DisplayName = displayName,
|
||||
TelegramUsername = telegramUsername
|
||||
},
|
||||
transaction);
|
||||
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO group_managers (group_id, player_id, role, added_by_player_id)
|
||||
SELECT @GroupId,
|
||||
co_gm.id,
|
||||
@CoGmRole,
|
||||
owner_player.id
|
||||
FROM players co_gm
|
||||
LEFT JOIN players owner_player ON owner_player.telegram_id = @OwnerTelegramId
|
||||
WHERE co_gm.telegram_id = @CoGmTelegramId
|
||||
ON CONFLICT (group_id, player_id) DO UPDATE
|
||||
SET role = CASE
|
||||
WHEN group_managers.role = @OwnerRole THEN group_managers.role
|
||||
ELSE EXCLUDED.role
|
||||
END,
|
||||
added_by_player_id = EXCLUDED.added_by_player_id
|
||||
""",
|
||||
new
|
||||
{
|
||||
GroupId = groupId,
|
||||
OwnerTelegramId = ownerTelegramId,
|
||||
CoGmTelegramId = coGmTelegramId,
|
||||
OwnerRole = GroupManagerRoleExtensions.OwnerValue,
|
||||
CoGmRole = GroupManagerRoleExtensions.CoGmValue
|
||||
},
|
||||
transaction);
|
||||
|
||||
await transaction.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task RemoveGroupCoGmAsync(Guid groupId, long coGmTelegramId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
DELETE FROM group_managers gm
|
||||
USING players p
|
||||
WHERE gm.player_id = p.id
|
||||
AND gm.group_id = @GroupId
|
||||
AND p.telegram_id = @CoGmTelegramId
|
||||
AND gm.role = @CoGmRole
|
||||
""",
|
||||
new
|
||||
{
|
||||
GroupId = groupId,
|
||||
CoGmTelegramId = coGmTelegramId,
|
||||
CoGmRole = GroupManagerRoleExtensions.CoGmValue
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<List<WebSession>> GetUpcomingSessionsAsync(Guid groupId)
|
||||
@@ -73,7 +313,8 @@ public sealed class SessionService(
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.max_players AS MaxPlayers,
|
||||
COALESCE(active_counts.count, 0)::int AS ActivePlayerCount,
|
||||
COALESCE(waitlist_counts.count, 0)::int AS WaitlistedPlayerCount
|
||||
COALESCE(waitlist_counts.count, 0)::int AS WaitlistedPlayerCount,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
LEFT JOIN LATERAL (
|
||||
@@ -109,7 +350,8 @@ public sealed class SessionService(
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.max_players AS MaxPlayers,
|
||||
COALESCE(active_counts.count, 0)::int AS ActivePlayerCount,
|
||||
COALESCE(waitlist_counts.count, 0)::int AS WaitlistedPlayerCount
|
||||
COALESCE(waitlist_counts.count, 0)::int AS WaitlistedPlayerCount,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
LEFT JOIN LATERAL (
|
||||
@@ -146,7 +388,8 @@ public sealed class SessionService(
|
||||
(array_agg(s.join_link ORDER BY s.scheduled_at))[1] AS JoinLink,
|
||||
MIN(s.scheduled_at) AS FirstScheduledAt,
|
||||
MAX(s.scheduled_at) AS LastScheduledAt,
|
||||
COUNT(*)::int AS SessionCount
|
||||
COUNT(*)::int AS SessionCount,
|
||||
(array_agg(s.notification_mode ORDER BY s.scheduled_at))[1] AS NotificationMode
|
||||
FROM sessions s
|
||||
WHERE s.batch_id = @BatchId
|
||||
GROUP BY s.batch_id, s.group_id
|
||||
@@ -165,7 +408,8 @@ public sealed class SessionService(
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.max_players AS MaxPlayers,
|
||||
0 AS ActivePlayerCount,
|
||||
0 AS WaitlistedPlayerCount
|
||||
0 AS WaitlistedPlayerCount,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.id = @Id AND s.group_id = @GroupId",
|
||||
@@ -183,6 +427,10 @@ public sealed class SessionService(
|
||||
scheduled_at = @ScheduledAt,
|
||||
join_link = @JoinLink,
|
||||
max_players = @MaxPlayers,
|
||||
one_hour_reminder_processed_at = CASE
|
||||
WHEN scheduled_at <> @ScheduledAt THEN NULL
|
||||
ELSE one_hour_reminder_processed_at
|
||||
END,
|
||||
updated_at = now()
|
||||
WHERE id = @Id AND group_id = @GroupId",
|
||||
new
|
||||
@@ -217,6 +465,13 @@ public sealed class SessionService(
|
||||
|
||||
await bot.SendMessage(oldSession.TelegramChatId, notification, parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(oldSession.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
var recipients = await LoadSessionDirectRecipientsAsync(conn, sessionId);
|
||||
await SendDirectNotificationsAsync(recipients, notification, "web-session-updated", sessionId);
|
||||
}
|
||||
|
||||
if (oldSession.BatchMessageId.HasValue)
|
||||
{
|
||||
await TryUpdateBatchMessageAsync(oldSession.BatchId, oldSession.TelegramChatId, oldSession.BatchMessageId.Value, title);
|
||||
@@ -234,7 +489,8 @@ public sealed class SessionService(
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.max_players AS MaxPlayers,
|
||||
0 AS ActivePlayerCount,
|
||||
0 AS WaitlistedPlayerCount
|
||||
0 AS WaitlistedPlayerCount,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.id = @SessionId AND s.group_id = @GroupId
|
||||
@@ -321,6 +577,148 @@ public sealed class SessionService(
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<WebParticipant>> GetSessionParticipantsAsync(Guid sessionId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
return (await conn.QueryAsync<WebParticipant>(
|
||||
"""
|
||||
SELECT sp.id AS Id,
|
||||
p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
sp.rsvp_status AS RsvpStatus,
|
||||
sp.registration_status AS RegistrationStatus,
|
||||
sp.is_gm AS IsGm,
|
||||
sp.responded_at AS RespondedAt
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
ORDER BY sp.is_gm DESC,
|
||||
CASE sp.registration_status WHEN 'Active' THEN 0 ELSE 1 END,
|
||||
sp.created_at
|
||||
""",
|
||||
new { SessionId = sessionId })).ToList();
|
||||
}
|
||||
|
||||
public async Task RemovePlayerFromSessionAsync(Guid sessionId, Guid groupId, Guid participantId)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
await using var transaction = await conn.BeginTransactionAsync();
|
||||
|
||||
var session = await conn.QuerySingleOrDefaultAsync<WebSession>(
|
||||
@"SELECT s.id, s.group_id AS GroupId, s.title, s.scheduled_at AS ScheduledAt, s.status, s.join_link AS JoinLink,
|
||||
s.batch_id AS BatchId, s.batch_message_id AS BatchMessageId,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.max_players AS MaxPlayers,
|
||||
0 AS ActivePlayerCount,
|
||||
0 AS WaitlistedPlayerCount,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.id = @SessionId AND s.group_id = @GroupId
|
||||
FOR UPDATE",
|
||||
new { SessionId = sessionId, GroupId = groupId },
|
||||
transaction);
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
throw new SessionAccessDeniedException(sessionId, 0);
|
||||
}
|
||||
|
||||
var participant = await conn.QuerySingleOrDefaultAsync<WebParticipant>(
|
||||
"""
|
||||
SELECT sp.id AS Id,
|
||||
p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
sp.rsvp_status AS RsvpStatus,
|
||||
sp.registration_status AS RegistrationStatus,
|
||||
sp.is_gm AS IsGm,
|
||||
sp.responded_at AS RespondedAt
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.id = @ParticipantId AND sp.session_id = @SessionId
|
||||
""",
|
||||
new { ParticipantId = participantId, SessionId = sessionId },
|
||||
transaction);
|
||||
|
||||
if (participant is null)
|
||||
{
|
||||
throw new InvalidOperationException("Участник не найден в этой сессии.");
|
||||
}
|
||||
|
||||
bool wasActive = participant.RegistrationStatus == ParticipantRegistrationStatus.Active;
|
||||
|
||||
await conn.ExecuteAsync(
|
||||
"DELETE FROM session_participants WHERE id = @ParticipantId",
|
||||
new { ParticipantId = participantId },
|
||||
transaction);
|
||||
|
||||
WebPromotedParticipantDto? promoted = null;
|
||||
|
||||
if (wasActive)
|
||||
{
|
||||
promoted = await conn.QuerySingleOrDefaultAsync<WebPromotedParticipantDto>(
|
||||
"""
|
||||
SELECT sp.id AS ParticipantRowId,
|
||||
p.display_name AS DisplayName
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Waitlisted
|
||||
ORDER BY sp.created_at ASC, sp.id ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE OF sp
|
||||
""",
|
||||
new { SessionId = sessionId, Waitlisted = ParticipantRegistrationStatus.Waitlisted },
|
||||
transaction);
|
||||
|
||||
if (promoted is not null)
|
||||
{
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
UPDATE session_participants
|
||||
SET registration_status = @Active,
|
||||
rsvp_status = @Pending,
|
||||
responded_at = NULL
|
||||
WHERE id = @ParticipantRowId
|
||||
""",
|
||||
new
|
||||
{
|
||||
promoted.ParticipantRowId,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Pending = RsvpStatus.Pending
|
||||
},
|
||||
transaction);
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.CommitAsync();
|
||||
|
||||
await bot.SendMessage(
|
||||
session.TelegramChatId,
|
||||
$"🚪 <b>{System.Net.WebUtility.HtmlEncode(participant.DisplayName)}</b> удален(а) из сессии «{System.Net.WebUtility.HtmlEncode(session.Title)}».",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
|
||||
if (promoted is not null)
|
||||
{
|
||||
await bot.SendMessage(
|
||||
session.TelegramChatId,
|
||||
$"⬆️ <b>{System.Net.WebUtility.HtmlEncode(promoted.DisplayName)}</b> переведен(а) из листа ожидания в основной состав «{System.Net.WebUtility.HtmlEncode(session.Title)}».",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
|
||||
if (session.BatchMessageId.HasValue)
|
||||
{
|
||||
await TryUpdateBatchMessageAsync(session.BatchId, session.TelegramChatId, session.BatchMessageId.Value, session.Title);
|
||||
}
|
||||
}
|
||||
else if (session.BatchMessageId.HasValue)
|
||||
{
|
||||
await TryUpdateBatchMessageAsync(session.BatchId, session.TelegramChatId, session.BatchMessageId.Value, session.Title);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task UpdateBatchDetailsAsync(Guid batchId, Guid groupId, string title, string joinLink)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
@@ -363,6 +761,41 @@ public sealed class SessionService(
|
||||
}
|
||||
}
|
||||
|
||||
public async Task UpdateBatchNotificationModeAsync(Guid batchId, Guid groupId, SessionNotificationMode notificationMode)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
await using var transaction = await conn.BeginTransactionAsync();
|
||||
|
||||
var batch = await GetBatchInfoAsync(conn, batchId, groupId, transaction);
|
||||
if (batch is null)
|
||||
{
|
||||
throw new SessionAccessDeniedException(batchId, 0);
|
||||
}
|
||||
|
||||
var updatedRows = await conn.ExecuteAsync(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET notification_mode = @NotificationMode,
|
||||
updated_at = now()
|
||||
WHERE batch_id = @BatchId
|
||||
AND group_id = @GroupId
|
||||
""",
|
||||
new
|
||||
{
|
||||
BatchId = batchId,
|
||||
GroupId = groupId,
|
||||
NotificationMode = notificationMode.ToDatabaseValue()
|
||||
},
|
||||
transaction);
|
||||
|
||||
if (updatedRows == 0)
|
||||
{
|
||||
throw new SessionAccessDeniedException(batchId, 0);
|
||||
}
|
||||
|
||||
await transaction.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task RescheduleBatchAsync(Guid batchId, Guid groupId, DateTime firstScheduledAt, int intervalDays)
|
||||
{
|
||||
await using var conn = await dataSource.OpenConnectionAsync();
|
||||
@@ -379,7 +812,8 @@ public sealed class SessionService(
|
||||
s.max_players AS MaxPlayers,
|
||||
s.batch_message_id AS BatchMessageId,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.thread_id AS ThreadId
|
||||
s.thread_id AS ThreadId,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.batch_id = @BatchId
|
||||
@@ -406,6 +840,7 @@ public sealed class SessionService(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET scheduled_at = @ScheduledAt,
|
||||
one_hour_reminder_processed_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE id = @SessionId
|
||||
""",
|
||||
@@ -431,6 +866,13 @@ public sealed class SessionService(
|
||||
$"↔️ Шаг: <b>{intervalDays} дн.</b>";
|
||||
|
||||
await bot.SendMessage(firstSession.TelegramChatId, notification, parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(firstSession.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
{
|
||||
var recipients = await LoadBatchDirectRecipientsAsync(conn, batchId);
|
||||
await SendDirectNotificationsAsync(recipients, notification, "web-batch-rescheduled", batchId);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WebSessionBatch> CloneBatchAsync(Guid batchId, Guid groupId, BatchCloneInterval interval)
|
||||
@@ -449,7 +891,8 @@ public sealed class SessionService(
|
||||
s.max_players AS MaxPlayers,
|
||||
s.batch_message_id AS BatchMessageId,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
s.thread_id AS ThreadId
|
||||
s.thread_id AS ThreadId,
|
||||
s.notification_mode AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.batch_id = @BatchId
|
||||
@@ -477,8 +920,8 @@ public sealed class SessionService(
|
||||
var scheduledAt = BatchSchedulePlanner.ShiftForClone(sourceSession.ScheduledAt, interval);
|
||||
var sessionId = await conn.ExecuteScalarAsync<Guid>(
|
||||
"""
|
||||
INSERT INTO sessions (batch_id, group_id, title, join_link, scheduled_at, status, thread_id, max_players)
|
||||
VALUES (@BatchId, @GroupId, @Title, @JoinLink, @ScheduledAt, @Status, @ThreadId, @MaxPlayers)
|
||||
INSERT INTO sessions (batch_id, group_id, title, join_link, scheduled_at, status, thread_id, max_players, notification_mode)
|
||||
VALUES (@BatchId, @GroupId, @Title, @JoinLink, @ScheduledAt, @Status, @ThreadId, @MaxPlayers, @NotificationMode)
|
||||
RETURNING id
|
||||
""",
|
||||
new
|
||||
@@ -490,7 +933,8 @@ public sealed class SessionService(
|
||||
ScheduledAt = scheduledAt,
|
||||
Status = SessionStatus.Planned,
|
||||
ThreadId = threadId,
|
||||
sourceSession.MaxPlayers
|
||||
sourceSession.MaxPlayers,
|
||||
sourceSession.NotificationMode
|
||||
},
|
||||
transaction);
|
||||
|
||||
@@ -499,7 +943,8 @@ public sealed class SessionService(
|
||||
|
||||
await transaction.CommitAsync();
|
||||
|
||||
var renderResult = SessionBatchRenderer.Render(batchTitle, renderedSessions, Array.Empty<ParticipantBatchDto>());
|
||||
var view = SessionBatchViewBuilder.Build(batchTitle, renderedSessions, Array.Empty<ParticipantBatchDto>());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
var batchMessage = await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: threadId,
|
||||
@@ -518,7 +963,279 @@ public sealed class SessionService(
|
||||
batchJoinLink,
|
||||
renderedSessions.Min(session => session.ScheduledAt),
|
||||
renderedSessions.Max(session => session.ScheduledAt),
|
||||
renderedSessions.Count);
|
||||
renderedSessions.Count,
|
||||
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 view = SessionBatchViewBuilder.Build(template.Title, renderedSessions, Array.Empty<ParticipantBatchDto>());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
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)
|
||||
{
|
||||
return (await conn.QueryAsync<WebDirectNotificationRecipient>(
|
||||
"""
|
||||
SELECT p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
""",
|
||||
new { SessionId = sessionId, Active = ParticipantRegistrationStatus.Active })).ToList();
|
||||
}
|
||||
|
||||
private async Task<List<WebDirectNotificationRecipient>> LoadBatchDirectRecipientsAsync(
|
||||
Npgsql.NpgsqlConnection conn,
|
||||
Guid batchId)
|
||||
{
|
||||
return (await conn.QueryAsync<WebDirectNotificationRecipient>(
|
||||
"""
|
||||
SELECT DISTINCT p.telegram_id AS TelegramId,
|
||||
p.display_name AS DisplayName
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
JOIN sessions s ON s.id = sp.session_id
|
||||
WHERE s.batch_id = @BatchId
|
||||
AND sp.is_gm = false
|
||||
AND sp.registration_status = @Active
|
||||
""",
|
||||
new { BatchId = batchId, Active = ParticipantRegistrationStatus.Active })).ToList();
|
||||
}
|
||||
|
||||
private async Task SendDirectNotificationsAsync(
|
||||
IEnumerable<WebDirectNotificationRecipient> recipients,
|
||||
string htmlText,
|
||||
string notificationKind,
|
||||
Guid entityId)
|
||||
{
|
||||
foreach (var recipient in recipients)
|
||||
{
|
||||
try
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: recipient.TelegramId,
|
||||
text: htmlText,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(
|
||||
ex,
|
||||
"Failed to send {NotificationKind} DM for entity {EntityId} to player {TelegramId} ({DisplayName})",
|
||||
notificationKind,
|
||||
entityId,
|
||||
recipient.TelegramId,
|
||||
recipient.DisplayName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryUpdateBatchMessageAsync(Guid batchId, long chatId, int messageId, string title)
|
||||
@@ -543,13 +1260,14 @@ public sealed class SessionService(
|
||||
ORDER BY sp.registration_status ASC, sp.created_at ASC, sp.responded_at ASC, p.created_at ASC",
|
||||
new { BatchId = batchId })).ToList();
|
||||
|
||||
var renderResult = SessionBatchRenderer.Render(title, sessions, participants);
|
||||
var view = SessionBatchViewBuilder.Build(title, sessions, participants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await bot.EditMessageText(
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
text: renderResult.Text,
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -572,7 +1290,8 @@ public sealed class SessionService(
|
||||
(array_agg(s.join_link ORDER BY s.scheduled_at))[1] AS JoinLink,
|
||||
g.telegram_chat_id AS TelegramChatId,
|
||||
(array_agg(s.batch_message_id ORDER BY s.scheduled_at))[1] AS BatchMessageId,
|
||||
(array_agg(s.thread_id ORDER BY s.scheduled_at))[1] AS ThreadId
|
||||
(array_agg(s.thread_id ORDER BY s.scheduled_at))[1] AS ThreadId,
|
||||
(array_agg(s.notification_mode ORDER BY s.scheduled_at))[1] AS NotificationMode
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON g.id = s.group_id
|
||||
WHERE s.batch_id = @BatchId
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public sealed class SubscriptionNotFoundException : Exception
|
||||
{
|
||||
public SubscriptionNotFoundException() : base("Calendar subscription not found.") { }
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
@@ -55,4 +58,170 @@ public sealed class TelegramAuthService(IConfiguration configuration)
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool VerifyWebAppInitData(string initData, out long telegramId, out string name)
|
||||
{
|
||||
telegramId = 0;
|
||||
name = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(initData))
|
||||
return false;
|
||||
|
||||
var token = configuration["Telegram__BotToken"] ?? configuration["Telegram:BotToken"];
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return false;
|
||||
|
||||
var values = QueryHelpers.ParseQuery(initData);
|
||||
if (!values.TryGetValue("hash", out var hash) || string.IsNullOrWhiteSpace(hash))
|
||||
return false;
|
||||
|
||||
var dataCheckString = string.Join(
|
||||
"\n",
|
||||
values
|
||||
.Where(pair => pair.Key != "hash")
|
||||
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
|
||||
.Select(pair => $"{pair.Key}={pair.Value}"));
|
||||
|
||||
var secretKey = HMACSHA256.HashData(Encoding.UTF8.GetBytes("WebAppData"), Encoding.UTF8.GetBytes(token));
|
||||
var computedHashBytes = HMACSHA256.HashData(secretKey, Encoding.UTF8.GetBytes(dataCheckString));
|
||||
|
||||
byte[] hashBytes;
|
||||
try
|
||||
{
|
||||
hashBytes = Convert.FromHexString(hash.ToString());
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CryptographicOperations.FixedTimeEquals(computedHashBytes, hashBytes))
|
||||
return false;
|
||||
|
||||
if (!values.TryGetValue("auth_date", out var authDateStr) ||
|
||||
!long.TryParse(authDateStr, out var authDate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
if (now - authDate > 86400)
|
||||
return false;
|
||||
|
||||
if (!values.TryGetValue("user", out var userJson) || string.IsNullOrWhiteSpace(userJson))
|
||||
return false;
|
||||
|
||||
return TryReadWebAppUser(userJson.ToString(), out telegramId, out name);
|
||||
}
|
||||
|
||||
public bool VerifyLoginPayload(TelegramLoginPayload payload, out long telegramId, out string name)
|
||||
{
|
||||
telegramId = 0;
|
||||
name = string.Empty;
|
||||
|
||||
if (payload.Id <= 0 ||
|
||||
string.IsNullOrWhiteSpace(payload.FirstName) ||
|
||||
payload.AuthDate <= 0 ||
|
||||
string.IsNullOrWhiteSpace(payload.Hash))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = configuration["Telegram__BotToken"] ?? configuration["Telegram:BotToken"];
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return false;
|
||||
|
||||
var values = new SortedDictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["auth_date"] = payload.AuthDate.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["first_name"] = payload.FirstName,
|
||||
["id"] = payload.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(payload.LastName))
|
||||
values["last_name"] = payload.LastName;
|
||||
if (!string.IsNullOrWhiteSpace(payload.PhotoUrl))
|
||||
values["photo_url"] = payload.PhotoUrl;
|
||||
if (!string.IsNullOrWhiteSpace(payload.Username))
|
||||
values["username"] = payload.Username;
|
||||
|
||||
var dataCheckString = string.Join("\n", values.Select(pair => $"{pair.Key}={pair.Value}"));
|
||||
var secretKey = SHA256.HashData(Encoding.UTF8.GetBytes(token));
|
||||
var computedHashBytes = HMACSHA256.HashData(secretKey, Encoding.UTF8.GetBytes(dataCheckString));
|
||||
|
||||
byte[] hashBytes;
|
||||
try
|
||||
{
|
||||
hashBytes = Convert.FromHexString(payload.Hash);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CryptographicOperations.FixedTimeEquals(computedHashBytes, hashBytes))
|
||||
return false;
|
||||
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
if (now - payload.AuthDate > 86400)
|
||||
return false;
|
||||
|
||||
telegramId = payload.Id;
|
||||
name = string.IsNullOrWhiteSpace(payload.LastName)
|
||||
? payload.FirstName
|
||||
: $"{payload.FirstName} {payload.LastName}";
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadWebAppUser(string userJson, out long telegramId, out string name)
|
||||
{
|
||||
telegramId = 0;
|
||||
name = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(userJson);
|
||||
var root = document.RootElement;
|
||||
|
||||
if (!root.TryGetProperty("id", out var idElement) || !idElement.TryGetInt64(out telegramId))
|
||||
return false;
|
||||
|
||||
var firstName = root.TryGetProperty("first_name", out var firstNameElement)
|
||||
? firstNameElement.GetString() ?? string.Empty
|
||||
: string.Empty;
|
||||
var lastName = root.TryGetProperty("last_name", out var lastNameElement)
|
||||
? lastNameElement.GetString() ?? string.Empty
|
||||
: string.Empty;
|
||||
var username = root.TryGetProperty("username", out var usernameElement)
|
||||
? usernameElement.GetString()
|
||||
: null;
|
||||
|
||||
name = (firstName, lastName) switch
|
||||
{
|
||||
({ Length: > 0 }, { Length: > 0 }) => $"{firstName} {lastName}",
|
||||
({ Length: > 0 }, _) => firstName,
|
||||
_ when !string.IsNullOrWhiteSpace(username) => "@" + username,
|
||||
_ => $"Telegram {telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture)}"
|
||||
};
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TelegramLoginPayload(
|
||||
[property: JsonPropertyName("id")] long Id,
|
||||
[property: JsonPropertyName("first_name")] string FirstName,
|
||||
[property: JsonPropertyName("last_name")] string? LastName,
|
||||
[property: JsonPropertyName("username")] string? Username,
|
||||
[property: JsonPropertyName("photo_url")] string? PhotoUrl,
|
||||
[property: JsonPropertyName("auth_date")] long AuthDate,
|
||||
[property: JsonPropertyName("hash")] string Hash);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
|
||||
public static class TelegramSessionBatchRenderer
|
||||
{
|
||||
public static (string Text, InlineKeyboardMarkup Markup) Render(SessionBatchViewModel view)
|
||||
{
|
||||
var messageText = $"🎲 <b>Новые игры:</b> {System.Net.WebUtility.HtmlEncode(view.Title)}\n\n" +
|
||||
$"<b>Расписание:</b>\n\n";
|
||||
|
||||
var buttons = new List<InlineKeyboardButton[]>();
|
||||
|
||||
foreach (var session in view.Sessions)
|
||||
{
|
||||
messageText += $"📅 <b>{session.ScheduledAt.FormatMoscow()}</b>\n";
|
||||
messageText += session.MaxPlayers.HasValue
|
||||
? $"👥 Места: {session.ActivePlayerCount}/{session.MaxPlayers.Value}\n"
|
||||
: $"👥 Игроки ({session.ActivePlayerCount}):\n";
|
||||
|
||||
if (session.ActivePlayers.Count > 0)
|
||||
{
|
||||
messageText += string.Join("\n", session.ActivePlayers.Select(p =>
|
||||
$" 👤 {(p.TelegramUsername != null ? "@" + p.TelegramUsername : p.DisplayName)}")) + "\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
messageText += " <i>Пока никто не записался</i>\n";
|
||||
}
|
||||
|
||||
if (session.WaitlistedPlayers.Count > 0)
|
||||
{
|
||||
messageText += $"⏳ Лист ожидания ({session.WaitlistedPlayers.Count}):\n";
|
||||
messageText += string.Join("\n", session.WaitlistedPlayers.Select(p =>
|
||||
$" ⏱ {(p.TelegramUsername != null ? "@" + p.TelegramUsername : p.DisplayName)}")) + "\n";
|
||||
}
|
||||
|
||||
if (GmRelay.Shared.Domain.SessionStatus.IsCancelled(session.Status))
|
||||
{
|
||||
messageText += "❌ <i>Сессия отменена</i>\n\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
messageText += "\n";
|
||||
var actionRow = session.AvailableActions
|
||||
.Select(a => InlineKeyboardButton.WithCallbackData(a.Label, $"{a.ActionKey}:{a.SessionId}"))
|
||||
.ToArray();
|
||||
if (actionRow.Length > 0)
|
||||
buttons.Add(actionRow);
|
||||
}
|
||||
}
|
||||
|
||||
return (messageText, new InlineKeyboardMarkup(buttons));
|
||||
}
|
||||
}
|
||||
+329
-53
@@ -1,5 +1,5 @@
|
||||
/* ============================================
|
||||
GM-Relay Design System v1.4.0
|
||||
GM-Relay Design System v1.9.9
|
||||
Dark RPG Dashboard Theme
|
||||
============================================ */
|
||||
|
||||
@@ -69,6 +69,21 @@
|
||||
|
||||
/* Sidebar */
|
||||
--sidebar-width: 260px;
|
||||
|
||||
/* Telegram Mini App safe areas */
|
||||
--gm-tg-safe-top: var(--tg-safe-area-inset-top, env(safe-area-inset-top, 0px));
|
||||
--gm-tg-safe-right: var(--tg-safe-area-inset-right, env(safe-area-inset-right, 0px));
|
||||
--gm-tg-safe-bottom: var(--tg-safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
|
||||
--gm-tg-safe-left: var(--tg-safe-area-inset-left, env(safe-area-inset-left, 0px));
|
||||
--gm-tg-content-safe-top: var(--tg-content-safe-area-inset-top, 0px);
|
||||
--gm-tg-content-safe-right: var(--tg-content-safe-area-inset-right, 0px);
|
||||
--gm-tg-content-safe-bottom: var(--tg-content-safe-area-inset-bottom, 0px);
|
||||
--gm-tg-content-safe-left: var(--tg-content-safe-area-inset-left, 0px);
|
||||
--gm-mini-app-top-inset: calc(var(--gm-tg-safe-top, 0px) + var(--gm-tg-content-safe-top, 0px));
|
||||
--gm-mini-app-bottom-inset: calc(var(--gm-tg-safe-bottom, 0px) + var(--gm-tg-content-safe-bottom, 0px));
|
||||
--gm-mini-app-left-inset: calc(var(--gm-tg-safe-left, 0px) + var(--gm-tg-content-safe-left, 0px));
|
||||
--gm-mini-app-right-inset: calc(var(--gm-tg-safe-right, 0px) + var(--gm-tg-content-safe-right, 0px));
|
||||
--gm-tg-viewport-height: 100dvh;
|
||||
}
|
||||
|
||||
/* === Reset & Base === */
|
||||
@@ -363,6 +378,11 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
filter: invert(0.7);
|
||||
}
|
||||
|
||||
select option {
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* === Tables === */
|
||||
.gm-table {
|
||||
width: 100%;
|
||||
@@ -402,6 +422,46 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.session-table-desktop {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
|
||||
.session-table-desktop-card {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.session-table-desktop .gm-table {
|
||||
min-width: 760px;
|
||||
}
|
||||
|
||||
.session-table-desktop .gm-table th:last-child,
|
||||
.session-table-desktop .gm-table td:last-child {
|
||||
width: 8.5rem;
|
||||
min-width: 8.5rem;
|
||||
}
|
||||
|
||||
.session-join-link {
|
||||
display: inline-block;
|
||||
max-width: 150px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.session-table-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.session-table-actions .btn-gm {
|
||||
font-size: 0.8125rem;
|
||||
padding: 0.375rem 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* === Alerts === */
|
||||
.gm-alert {
|
||||
padding: 0.875rem 1.125rem;
|
||||
@@ -613,6 +673,78 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* === Campaign templates === */
|
||||
.campaign-template-panel {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.campaign-template-fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.campaign-template-list {
|
||||
margin-top: 1rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.campaign-template-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(360px, auto);
|
||||
gap: 1rem;
|
||||
align-items: center;
|
||||
padding: 1rem 0;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.campaign-template-row:last-child {
|
||||
border-bottom: none;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.campaign-template-info h3 {
|
||||
font-size: 0.9375rem;
|
||||
margin-bottom: 0.25rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.campaign-template-info p {
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.campaign-template-actions {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(190px, 1fr) auto;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.template-group-selector {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.template-management-row {
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
}
|
||||
|
||||
.template-management-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.empty-state-compact {
|
||||
padding: 1.5rem 1rem;
|
||||
}
|
||||
|
||||
/* === Animations === */
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
@@ -765,12 +897,125 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
/* === Telegram Mini App entry === */
|
||||
.mini-app-page {
|
||||
min-height: 100vh;
|
||||
min-height: var(--gm-tg-viewport-height, 100dvh);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.mini-app-auth-card {
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
padding: 1.5rem;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--glass-bg);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.mini-app-logo {
|
||||
font-size: 2.25rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.mini-app-auth-card h1 {
|
||||
font-size: 1.375rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.mini-app-auth-card p {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.875rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.telegram-mini-app .page-container {
|
||||
max-width: 720px;
|
||||
}
|
||||
|
||||
body.telegram-mini-app {
|
||||
min-height: var(--gm-tg-viewport-height, 100dvh);
|
||||
}
|
||||
|
||||
body.telegram-mini-app .mini-app-page {
|
||||
padding-top: calc(1rem + var(--gm-mini-app-top-inset, 0px));
|
||||
padding-right: calc(1rem + var(--gm-mini-app-right-inset, 0px));
|
||||
padding-bottom: calc(1rem + var(--gm-mini-app-bottom-inset, 0px));
|
||||
padding-left: calc(1rem + var(--gm-mini-app-left-inset, 0px));
|
||||
}
|
||||
|
||||
body.telegram-mini-app .content {
|
||||
padding-bottom: calc(1.5rem + var(--gm-mini-app-bottom-inset, 0px));
|
||||
}
|
||||
|
||||
/* === Mobile Sessions Cards (instead of table) === */
|
||||
.session-card-mobile {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
body.telegram-mini-app .session-table-desktop {
|
||||
display: none;
|
||||
}
|
||||
|
||||
body.telegram-mini-app .session-card-mobile {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.session-card {
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1rem;
|
||||
margin-bottom: 0.75rem;
|
||||
transition: all var(--transition-smooth);
|
||||
}
|
||||
|
||||
.session-card:hover {
|
||||
border-color: var(--border-glow);
|
||||
}
|
||||
|
||||
.session-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.session-card-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.session-card-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.session-card-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.session-card-actions {
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.session-table-desktop {
|
||||
display: none;
|
||||
}
|
||||
@@ -778,66 +1023,24 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
.session-card-mobile {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.session-card {
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1rem;
|
||||
margin-bottom: 0.75rem;
|
||||
transition: all var(--transition-smooth);
|
||||
}
|
||||
|
||||
.session-card:hover {
|
||||
border-color: var(--border-glow);
|
||||
}
|
||||
|
||||
.session-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.session-card-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.session-card-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.session-card-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.session-card-actions {
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.card-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.batch-bulk-fields,
|
||||
.batch-clone-row {
|
||||
.batch-clone-row,
|
||||
.campaign-template-fields,
|
||||
.campaign-template-row,
|
||||
.campaign-template-actions,
|
||||
.template-group-selector {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.batch-clone-row .btn-gm {
|
||||
.batch-clone-row .btn-gm,
|
||||
.campaign-template-actions .btn-gm {
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
@@ -846,6 +1049,26 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.telegram-mini-app .content {
|
||||
padding: 0.75rem;
|
||||
padding-bottom: calc(0.75rem + var(--gm-mini-app-bottom-inset, 0px));
|
||||
}
|
||||
|
||||
.telegram-mini-app .page-container {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
body.telegram-mini-app .nav-header {
|
||||
padding-top: calc(1.25rem + var(--gm-mini-app-top-inset, 0px));
|
||||
padding-left: calc(1rem + var(--gm-mini-app-left-inset, 0px));
|
||||
padding-right: calc(0.75rem + var(--gm-mini-app-right-inset, 0px));
|
||||
}
|
||||
|
||||
body.telegram-mini-app .nav-toggle {
|
||||
top: calc(0.75rem + var(--gm-mini-app-top-inset, 0px));
|
||||
left: calc(0.75rem + var(--gm-mini-app-left-inset, 0px));
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
@@ -892,3 +1115,56 @@ input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Participant list === */
|
||||
.participant-panel {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 0.75rem;
|
||||
padding: 0.75rem;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.participant-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.participant-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-radius: 0.5rem;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.participant-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.participant-name {
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.participant-username {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.btn-gm-link {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
font-size: inherit;
|
||||
font-family: inherit;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Domain;
|
||||
|
||||
public sealed class SessionNotificationModeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(SessionNotificationMode.GroupAndDirect, true)]
|
||||
[InlineData(SessionNotificationMode.GroupOnly, false)]
|
||||
public void ShouldSendDirectMessages_ReturnsExpectedDecision(
|
||||
SessionNotificationMode mode,
|
||||
bool expected)
|
||||
{
|
||||
Assert.Equal(expected, mode.ShouldSendDirectMessages());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Landing;
|
||||
|
||||
public sealed class TelegramLandingPromisesSmokeTests
|
||||
{
|
||||
[Fact]
|
||||
public void Smoke_ShouldCoverTelegramLandingPromisesWithoutExternalTelegramApi()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 5, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
var parseResult = NewSessionCommandParser.Parse(BuildRecurringSessionCommand(), nowUtc);
|
||||
|
||||
Assert.True(parseResult.IsValid);
|
||||
Assert.Equal(3, parseResult.ScheduledTimes.Count);
|
||||
Assert.Equal(2, parseResult.MaxPlayers);
|
||||
Assert.Equal(TimeSpan.FromDays(7), parseResult.ScheduledTimes[1] - parseResult.ScheduledTimes[0]);
|
||||
|
||||
var scenario = TelegramLandingSmokeScenario.Publish(parseResult, SessionNotificationMode.GroupAndDirect);
|
||||
var publishedCallbacks = CallbackData(scenario.LastMessage.Markup);
|
||||
|
||||
Assert.Contains("Landing Promise Smoke", scenario.LastMessage.Text);
|
||||
Assert.Equal(6, publishedCallbacks.Count);
|
||||
Assert.All(scenario.Sessions, session =>
|
||||
{
|
||||
Assert.Contains($"join_session:{session.Id}", publishedCallbacks);
|
||||
Assert.Contains($"leave_session:{session.Id}", publishedCallbacks);
|
||||
Assert.Contains(session.ScheduledAt.FormatMoscow(), scenario.LastMessage.Text);
|
||||
});
|
||||
|
||||
var firstSessionId = scenario.Sessions[0].Id;
|
||||
var alice = scenario.Join(firstSessionId, 1001, "Alice", "alice");
|
||||
var bob = scenario.Join(firstSessionId, 1002, "Bob", "bob");
|
||||
var carol = scenario.Join(firstSessionId, 1003, "Carol", "carol");
|
||||
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, alice));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, bob));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Waitlisted, scenario.RegistrationStatus(firstSessionId, carol));
|
||||
Assert.Contains("2/2", scenario.LastMessage.Text);
|
||||
Assert.Contains("@alice", scenario.LastMessage.Text);
|
||||
Assert.Contains("@bob", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
|
||||
scenario.Leave(firstSessionId, alice);
|
||||
|
||||
Assert.False(scenario.HasParticipant(firstSessionId, alice));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, carol));
|
||||
Assert.DoesNotContain("@alice", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
|
||||
scenario.MarkRsvpConfirmed(firstSessionId, bob);
|
||||
scenario.MarkRsvpConfirmed(firstSessionId, carol);
|
||||
|
||||
var option1Id = Guid.NewGuid();
|
||||
var option2Id = Guid.NewGuid();
|
||||
var options = new[]
|
||||
{
|
||||
new RescheduleOptionDto(option1Id, 1, new DateTimeOffset(2026, 5, 29, 16, 30, 0, TimeSpan.Zero)),
|
||||
new RescheduleOptionDto(option2Id, 2, new DateTimeOffset(2026, 5, 30, 15, 0, 0, TimeSpan.Zero))
|
||||
};
|
||||
var deadline = new DateTimeOffset(2026, 5, 20, 18, 0, 0, TimeSpan.Zero);
|
||||
var voteParticipants = scenario.ActiveVoteParticipants(firstSessionId);
|
||||
var voteMessage = HandleRescheduleTimeInputHandler.BuildVotingMessage(
|
||||
scenario.Title,
|
||||
scenario.Sessions[0].ScheduledAt,
|
||||
deadline,
|
||||
options,
|
||||
voteParticipants,
|
||||
[]);
|
||||
var voteKeyboard = HandleRescheduleTimeInputHandler.BuildVotingKeyboard(options);
|
||||
|
||||
Assert.Contains("Landing Promise Smoke", voteMessage);
|
||||
Assert.Contains("0/2", voteMessage);
|
||||
Assert.Contains($"reschedule_vote:{option1Id}", CallbackData(voteKeyboard));
|
||||
Assert.Contains($"reschedule_vote:{option2Id}", CallbackData(voteKeyboard));
|
||||
|
||||
var votes = voteParticipants
|
||||
.Select(participant => new RescheduleOptionVoteDto(
|
||||
option2Id,
|
||||
participant.PlayerId,
|
||||
participant.DisplayName,
|
||||
participant.TelegramUsername))
|
||||
.ToList();
|
||||
var decision = RescheduleVoteRules.SelectWinner(
|
||||
options.Select(option => new RescheduleOptionVoteCount(
|
||||
option.OptionId,
|
||||
votes.Count(vote => vote.OptionId == option.OptionId))).ToList());
|
||||
|
||||
Assert.Equal(RescheduleVoteOutcome.Approved, decision.Outcome);
|
||||
Assert.Equal(option2Id, decision.SelectedOptionId);
|
||||
|
||||
scenario.ApplyReschedule(firstSessionId, options[1].ProposedAt);
|
||||
|
||||
Assert.Equal(options[1].ProposedAt.UtcDateTime, scenario.Sessions[0].ScheduledAt);
|
||||
Assert.Equal(RsvpStatus.Pending, scenario.RsvpStatus(firstSessionId, bob));
|
||||
Assert.Equal(RsvpStatus.Pending, scenario.RsvpStatus(firstSessionId, carol));
|
||||
Assert.Contains(options[1].ProposedAt.UtcDateTime.FormatMoscow(), scenario.LastMessage.Text);
|
||||
Assert.Collection(
|
||||
scenario.Messenger.DirectMessages.Select(message => message.TelegramId).Order(),
|
||||
telegramId => Assert.Equal(1002, telegramId),
|
||||
telegramId => Assert.Equal(1003, telegramId));
|
||||
Assert.All(scenario.Messenger.DirectMessages, message =>
|
||||
{
|
||||
Assert.Contains("Landing Promise Smoke", message.Text);
|
||||
Assert.Contains(options[1].ProposedAt.UtcDateTime.FormatMoscow(), message.Text);
|
||||
});
|
||||
|
||||
var editsBeforeDashboardUpdate = scenario.Messenger.Edits.Count;
|
||||
|
||||
scenario.UpdateBatchFromDashboard("Landing Promise Smoke - Dashboard Sync");
|
||||
|
||||
Assert.True(scenario.Messenger.Edits.Count > editsBeforeDashboardUpdate);
|
||||
Assert.Contains("Landing Promise Smoke - Dashboard Sync", scenario.LastMessage.Text);
|
||||
Assert.Contains("@bob", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
}
|
||||
|
||||
private static string BuildRecurringSessionCommand() =>
|
||||
string.Join(
|
||||
'\n',
|
||||
"/newsession",
|
||||
"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435: Landing Promise Smoke",
|
||||
"\u0412\u0440\u0435\u043c\u044f: 15.05.2026 19:30",
|
||||
"\u0418\u0433\u0440: 3",
|
||||
"\u0418\u043d\u0442\u0435\u0440\u0432\u0430\u043b: 7",
|
||||
"\u041c\u0435\u0441\u0442: 2",
|
||||
"\u0421\u0441\u044b\u043b\u043a\u0430: https://example.test/table");
|
||||
|
||||
private static IReadOnlyList<string> CallbackData(InlineKeyboardMarkup markup) =>
|
||||
markup.InlineKeyboard
|
||||
.SelectMany(row => row)
|
||||
.Select(button => button.CallbackData)
|
||||
.OfType<string>()
|
||||
.ToList();
|
||||
|
||||
private sealed class TelegramLandingSmokeScenario
|
||||
{
|
||||
private readonly List<SmokeSession> sessions;
|
||||
private readonly List<SmokeParticipant> participants = [];
|
||||
private readonly SessionNotificationMode notificationMode;
|
||||
|
||||
private TelegramLandingSmokeScenario(
|
||||
string title,
|
||||
IReadOnlyList<DateTimeOffset> scheduledTimes,
|
||||
int? maxPlayers,
|
||||
SessionNotificationMode notificationMode)
|
||||
{
|
||||
Title = title;
|
||||
this.notificationMode = notificationMode;
|
||||
sessions = scheduledTimes
|
||||
.Select(scheduledAt => new SmokeSession(
|
||||
Guid.NewGuid(),
|
||||
scheduledAt.UtcDateTime,
|
||||
SessionStatus.Planned,
|
||||
maxPlayers))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public string Title { get; private set; }
|
||||
public FakeTelegramMessenger Messenger { get; } = new();
|
||||
public IReadOnlyList<SmokeSession> Sessions => sessions;
|
||||
public FakeTelegramMessage LastMessage => Messenger.LastMessage;
|
||||
|
||||
public static TelegramLandingSmokeScenario Publish(
|
||||
NewSessionParseResult parseResult,
|
||||
SessionNotificationMode notificationMode)
|
||||
{
|
||||
var scenario = new TelegramLandingSmokeScenario(
|
||||
parseResult.Title!,
|
||||
parseResult.ScheduledTimes,
|
||||
parseResult.MaxPlayers,
|
||||
notificationMode);
|
||||
|
||||
scenario.RenderBatch();
|
||||
return scenario;
|
||||
}
|
||||
|
||||
public Guid Join(Guid sessionId, long telegramId, string displayName, string? telegramUsername)
|
||||
{
|
||||
var session = sessions.Single(value => value.Id == sessionId);
|
||||
var activeParticipants = participants.Count(participant =>
|
||||
participant.SessionId == sessionId &&
|
||||
participant.RegistrationStatus == ParticipantRegistrationStatus.Active);
|
||||
var registrationStatus = SessionCapacityRules.DecideJoinStatus(
|
||||
session.MaxPlayers,
|
||||
activeParticipants);
|
||||
var playerId = Guid.NewGuid();
|
||||
|
||||
participants.Add(new SmokeParticipant(
|
||||
sessionId,
|
||||
playerId,
|
||||
telegramId,
|
||||
displayName,
|
||||
telegramUsername,
|
||||
registrationStatus,
|
||||
GmRelay.Shared.Domain.RsvpStatus.Pending,
|
||||
participants.Count));
|
||||
|
||||
RenderBatch();
|
||||
return playerId;
|
||||
}
|
||||
|
||||
public void Leave(Guid sessionId, Guid playerId)
|
||||
{
|
||||
var participant = participants.Single(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.PlayerId == playerId);
|
||||
participants.Remove(participant);
|
||||
|
||||
var session = sessions.Single(value => value.Id == sessionId);
|
||||
var activeParticipantsAfterLeave = participants.Count(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.RegistrationStatus == ParticipantRegistrationStatus.Active);
|
||||
var waitlistedParticipants = participants.Count(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted);
|
||||
|
||||
if (SessionCapacityRules.ShouldPromoteAfterParticipantLeaves(
|
||||
participant.RegistrationStatus,
|
||||
session.MaxPlayers,
|
||||
activeParticipantsAfterLeave,
|
||||
waitlistedParticipants))
|
||||
{
|
||||
var promoted = participants
|
||||
.Where(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted)
|
||||
.OrderBy(value => value.JoinOrder)
|
||||
.First();
|
||||
|
||||
promoted.RegistrationStatus = ParticipantRegistrationStatus.Active;
|
||||
promoted.RsvpStatus = GmRelay.Shared.Domain.RsvpStatus.Pending;
|
||||
}
|
||||
|
||||
RenderBatch();
|
||||
}
|
||||
|
||||
public bool HasParticipant(Guid sessionId, Guid playerId) =>
|
||||
participants.Any(value => value.SessionId == sessionId && value.PlayerId == playerId);
|
||||
|
||||
public string RegistrationStatus(Guid sessionId, Guid playerId) =>
|
||||
participants.Single(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.PlayerId == playerId).RegistrationStatus;
|
||||
|
||||
public string RsvpStatus(Guid sessionId, Guid playerId) =>
|
||||
participants.Single(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.PlayerId == playerId).RsvpStatus;
|
||||
|
||||
public void MarkRsvpConfirmed(Guid sessionId, Guid playerId)
|
||||
{
|
||||
participants.Single(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.PlayerId == playerId).RsvpStatus = GmRelay.Shared.Domain.RsvpStatus.Confirmed;
|
||||
}
|
||||
|
||||
public IReadOnlyList<VoteParticipantDto> ActiveVoteParticipants(Guid sessionId) =>
|
||||
participants
|
||||
.Where(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.RegistrationStatus == ParticipantRegistrationStatus.Active)
|
||||
.OrderBy(value => value.DisplayName)
|
||||
.Select(value => new VoteParticipantDto(
|
||||
value.PlayerId,
|
||||
value.DisplayName,
|
||||
value.TelegramUsername,
|
||||
value.TelegramId))
|
||||
.ToList();
|
||||
|
||||
public void ApplyReschedule(Guid sessionId, DateTimeOffset newScheduledAt)
|
||||
{
|
||||
sessions.Single(value => value.Id == sessionId).ScheduledAt = newScheduledAt.UtcDateTime;
|
||||
|
||||
foreach (var participant in participants.Where(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.RegistrationStatus == ParticipantRegistrationStatus.Active))
|
||||
{
|
||||
participant.RsvpStatus = GmRelay.Shared.Domain.RsvpStatus.Pending;
|
||||
}
|
||||
|
||||
RenderBatch();
|
||||
|
||||
if (!notificationMode.ShouldSendDirectMessages())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var notification = $"""
|
||||
Reschedule approved
|
||||
{Title}
|
||||
{newScheduledAt.UtcDateTime.FormatMoscow()}
|
||||
""";
|
||||
foreach (var participant in participants.Where(value =>
|
||||
value.SessionId == sessionId &&
|
||||
value.RegistrationStatus == ParticipantRegistrationStatus.Active))
|
||||
{
|
||||
Messenger.SendDirectMessage(participant.TelegramId, notification);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateBatchFromDashboard(string title)
|
||||
{
|
||||
Title = title;
|
||||
RenderBatch();
|
||||
}
|
||||
|
||||
private void RenderBatch()
|
||||
{
|
||||
var view = SessionBatchViewBuilder.Build(
|
||||
Title,
|
||||
sessions
|
||||
.Select(session => new SessionBatchDto(
|
||||
session.Id,
|
||||
session.ScheduledAt,
|
||||
session.Status,
|
||||
session.MaxPlayers))
|
||||
.ToList(),
|
||||
participants
|
||||
.Select(participant => new ParticipantBatchDto(
|
||||
participant.SessionId,
|
||||
participant.DisplayName,
|
||||
participant.TelegramUsername,
|
||||
participant.RegistrationStatus))
|
||||
.ToList());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
if (Messenger.HasPublishedMessage)
|
||||
{
|
||||
Messenger.EditBatchMessage(renderResult.Text, renderResult.Markup);
|
||||
}
|
||||
else
|
||||
{
|
||||
Messenger.PublishBatchMessage(renderResult.Text, renderResult.Markup);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeTelegramMessenger
|
||||
{
|
||||
private const int BatchMessageId = 7001;
|
||||
|
||||
public List<FakeTelegramMessage> Sends { get; } = [];
|
||||
public List<FakeTelegramMessage> Edits { get; } = [];
|
||||
public List<FakeDirectMessage> DirectMessages { get; } = [];
|
||||
public bool HasPublishedMessage => Sends.Count > 0;
|
||||
public FakeTelegramMessage LastMessage => Edits.Count > 0 ? Edits[^1] : Sends[^1];
|
||||
|
||||
public void PublishBatchMessage(string text, InlineKeyboardMarkup markup) =>
|
||||
Sends.Add(new FakeTelegramMessage(BatchMessageId, text, markup));
|
||||
|
||||
public void EditBatchMessage(string text, InlineKeyboardMarkup markup) =>
|
||||
Edits.Add(new FakeTelegramMessage(BatchMessageId, text, markup));
|
||||
|
||||
public void SendDirectMessage(long telegramId, string text) =>
|
||||
DirectMessages.Add(new FakeDirectMessage(telegramId, text));
|
||||
}
|
||||
|
||||
private sealed record FakeTelegramMessage(
|
||||
int MessageId,
|
||||
string Text,
|
||||
InlineKeyboardMarkup Markup);
|
||||
|
||||
private sealed record FakeDirectMessage(long TelegramId, string Text);
|
||||
|
||||
private sealed record SmokeSession(
|
||||
Guid Id,
|
||||
DateTime ScheduledAt,
|
||||
string Status,
|
||||
int? MaxPlayers)
|
||||
{
|
||||
public DateTime ScheduledAt { get; set; } = ScheduledAt;
|
||||
}
|
||||
|
||||
private sealed record SmokeParticipant(
|
||||
Guid SessionId,
|
||||
Guid PlayerId,
|
||||
long TelegramId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
string RegistrationStatus,
|
||||
string RsvpStatus,
|
||||
int JoinOrder)
|
||||
{
|
||||
public string RegistrationStatus { get; set; } = RegistrationStatus;
|
||||
public string RsvpStatus { get; set; } = RsvpStatus;
|
||||
}
|
||||
}
|
||||
+64
@@ -1,4 +1,5 @@
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
@@ -33,6 +34,69 @@ public sealed class NewSessionCommandParserTests
|
||||
Assert.Empty(result.InvalidTimeInputs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ShouldExtractOptionalImageUrl()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 4, 23, 12, 0, 0, TimeSpan.Zero);
|
||||
var text = """
|
||||
/newsession
|
||||
Название: Curse of Strahd
|
||||
Время: 24.04.2026 19:30
|
||||
Ссылка: https://example.test/room
|
||||
Картинка: https://example.test/strahd.jpg
|
||||
""";
|
||||
|
||||
var result = NewSessionCommandParser.Parse(text, nowUtc);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal("https://example.test/strahd.jpg", result.ImageUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetBatchImageReference_ShouldPreferAttachedPhotoOverParsedUrl()
|
||||
{
|
||||
var message = new Message
|
||||
{
|
||||
Photo =
|
||||
[
|
||||
new PhotoSize { FileId = "small-photo", Width = 320, Height = 180, FileSize = 10 },
|
||||
new PhotoSize { FileId = "large-photo", Width = 1280, Height = 720, FileSize = 20 }
|
||||
]
|
||||
};
|
||||
|
||||
var imageReference = CreateSessionHandler.GetBatchImageReference(
|
||||
message,
|
||||
"https://example.test/cover.jpg");
|
||||
|
||||
Assert.Equal("large-photo", imageReference);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ShouldExpandRecurringSchedule_WhenRepeatCountAndIntervalProvided()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 4, 23, 12, 0, 0, TimeSpan.Zero);
|
||||
var text = """
|
||||
/newsession
|
||||
Название: Kingmaker
|
||||
Время: 30.04.2026 19:30
|
||||
Игр: 4
|
||||
Интервал: 14
|
||||
Ссылка: https://example.test/kingmaker
|
||||
""";
|
||||
|
||||
var result = NewSessionCommandParser.Parse(text, nowUtc);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal(
|
||||
[
|
||||
new DateTimeOffset(2026, 4, 30, 16, 30, 0, TimeSpan.Zero),
|
||||
new DateTimeOffset(2026, 5, 14, 16, 30, 0, TimeSpan.Zero),
|
||||
new DateTimeOffset(2026, 5, 28, 16, 30, 0, TimeSpan.Zero),
|
||||
new DateTimeOffset(2026, 6, 11, 16, 30, 0, TimeSpan.Zero)
|
||||
],
|
||||
result.ScheduledTimes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ShouldCollectPastAndInvalidTimes()
|
||||
{
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
using GmRelay.Bot.Features.Sessions.ListSessions;
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.ListSessions;
|
||||
|
||||
public sealed class SessionListMessageRendererTests
|
||||
{
|
||||
[Fact]
|
||||
public void Render_ShouldIncludeManagerActions_WhenUserCanManage()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionListItemDto(
|
||||
sessionId,
|
||||
"Ravenloft",
|
||||
new DateTime(2026, 5, 7, 16, 30, 0, DateTimeKind.Utc),
|
||||
SessionStatus.Planned,
|
||||
4,
|
||||
3,
|
||||
1,
|
||||
true)
|
||||
};
|
||||
|
||||
var result = SessionListMessageRenderer.Render(sessions);
|
||||
Assert.NotNull(result.Markup);
|
||||
var buttons = result.Markup.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
|
||||
Assert.Contains("Ravenloft", result.Text);
|
||||
Assert.Collection(
|
||||
buttons.Select(button => button.CallbackData),
|
||||
callbackData => Assert.Equal($"cancel_session:{sessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"reschedule_session:{sessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"promote_waitlist:{sessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"delete_session:{sessionId}", callbackData));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldHideManagerActions_WhenUserCannotManage()
|
||||
{
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionListItemDto(
|
||||
Guid.NewGuid(),
|
||||
"Ravenloft",
|
||||
new DateTime(2026, 5, 7, 16, 30, 0, DateTimeKind.Utc),
|
||||
SessionStatus.Planned,
|
||||
4,
|
||||
3,
|
||||
1,
|
||||
false)
|
||||
};
|
||||
|
||||
var result = SessionListMessageRenderer.Render(sessions);
|
||||
|
||||
Assert.Null(result.Markup);
|
||||
}
|
||||
}
|
||||
+98
-11
@@ -5,28 +5,115 @@ namespace GmRelay.Bot.Tests.Features.Sessions.RescheduleSession;
|
||||
public sealed class HandleRescheduleTimeInputHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public void BuildVotingMessage_ShouldShowApprovedAndPendingParticipants()
|
||||
public void TryParseVotingInput_ShouldAcceptTwoOptionsAndDeadline()
|
||||
{
|
||||
var approvedId = Guid.NewGuid();
|
||||
var pendingId = Guid.NewGuid();
|
||||
var now = new DateTimeOffset(2026, 4, 24, 8, 0, 0, TimeSpan.Zero);
|
||||
|
||||
var ok = RescheduleVotingInput.TryParse(
|
||||
"""
|
||||
25.04.2026 19:30
|
||||
26.04.2026 18:00
|
||||
Дедлайн: 25.04.2026 12:00
|
||||
""",
|
||||
now,
|
||||
out var input,
|
||||
out var error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(2, input.Options.Count);
|
||||
Assert.Equal(new DateTimeOffset(2026, 4, 25, 16, 30, 0, TimeSpan.Zero), input.Options[0]);
|
||||
Assert.Equal(new DateTimeOffset(2026, 4, 26, 15, 0, 0, TimeSpan.Zero), input.Options[1]);
|
||||
Assert.Equal(new DateTimeOffset(2026, 4, 25, 9, 0, 0, TimeSpan.Zero), input.Deadline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryParseVotingInput_ShouldRejectSingleOption()
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 4, 24, 8, 0, 0, TimeSpan.Zero);
|
||||
|
||||
var ok = RescheduleVotingInput.TryParse(
|
||||
"""
|
||||
25.04.2026 19:30
|
||||
Дедлайн: 25.04.2026 12:00
|
||||
""",
|
||||
now,
|
||||
out _,
|
||||
out var error);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("Укажите от 2 до 3 вариантов времени.", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildVotingMessage_ShouldShowOptionsDeadlineVotesAndPendingParticipants()
|
||||
{
|
||||
var firstOptionId = Guid.NewGuid();
|
||||
var secondOptionId = Guid.NewGuid();
|
||||
var aliceId = Guid.NewGuid();
|
||||
var bobId = Guid.NewGuid();
|
||||
var charlieId = Guid.NewGuid();
|
||||
var currentTime = new DateTime(2026, 4, 25, 16, 30, 0, DateTimeKind.Utc);
|
||||
var newTime = new DateTimeOffset(2026, 4, 26, 17, 0, 0, TimeSpan.Zero);
|
||||
var deadline = new DateTimeOffset(2026, 4, 25, 9, 0, 0, TimeSpan.Zero);
|
||||
var options = new List<RescheduleOptionDto>
|
||||
{
|
||||
new(firstOptionId, 1, new DateTimeOffset(2026, 4, 26, 16, 0, 0, TimeSpan.Zero)),
|
||||
new(secondOptionId, 2, new DateTimeOffset(2026, 4, 27, 17, 0, 0, TimeSpan.Zero))
|
||||
};
|
||||
var participants = new List<VoteParticipantDto>
|
||||
{
|
||||
new(approvedId, "Alice", "alice"),
|
||||
new(pendingId, "Bob", null)
|
||||
new(aliceId, "Alice", "alice"),
|
||||
new(bobId, "Bob", null),
|
||||
new(charlieId, "Charlie", null)
|
||||
};
|
||||
var votes = new List<RescheduleOptionVoteDto>
|
||||
{
|
||||
new(firstOptionId, aliceId, "Alice", "alice"),
|
||||
new(secondOptionId, bobId, "Bob", null)
|
||||
};
|
||||
|
||||
var text = HandleRescheduleTimeInputHandler.BuildVotingMessage(
|
||||
"Shadowrun",
|
||||
currentTime,
|
||||
newTime,
|
||||
deadline,
|
||||
options,
|
||||
participants,
|
||||
[approvedId]);
|
||||
votes);
|
||||
|
||||
Assert.Contains("Shadowrun", text);
|
||||
Assert.Contains("✅ @alice", text);
|
||||
Assert.Contains("⏳ Bob", text);
|
||||
Assert.Contains("Голоса: 1/2 ✅", text);
|
||||
Assert.Contains("Дедлайн: <b>25 апреля 2026, 12:00</b> (МСК)", text);
|
||||
Assert.Contains("1. <b>26 апреля 2026, 19:00</b> (МСК) — 1 голос", text);
|
||||
Assert.Contains("@alice", text);
|
||||
Assert.Contains("2. <b>27 апреля 2026, 20:00</b> (МСК) — 1 голос", text);
|
||||
Assert.Contains("Bob", text);
|
||||
Assert.Contains("Не проголосовали: Charlie", text);
|
||||
Assert.Contains("Голосов: 2/3", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildVotingKeyboard_ShouldCreateOneButtonPerOption()
|
||||
{
|
||||
var firstOptionId = Guid.NewGuid();
|
||||
var secondOptionId = Guid.NewGuid();
|
||||
var options = new List<RescheduleOptionDto>
|
||||
{
|
||||
new(firstOptionId, 1, new DateTimeOffset(2026, 4, 26, 16, 0, 0, TimeSpan.Zero)),
|
||||
new(secondOptionId, 2, new DateTimeOffset(2026, 4, 27, 17, 0, 0, TimeSpan.Zero))
|
||||
};
|
||||
|
||||
var keyboard = HandleRescheduleTimeInputHandler.BuildVotingKeyboard(options);
|
||||
var buttons = keyboard.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
|
||||
Assert.Collection(
|
||||
buttons,
|
||||
button =>
|
||||
{
|
||||
Assert.Equal("1. 26.04 19:00", button.Text);
|
||||
Assert.Equal($"reschedule_vote:{firstOptionId}", button.CallbackData);
|
||||
},
|
||||
button =>
|
||||
{
|
||||
Assert.Equal("2. 27.04 20:00", button.Text);
|
||||
Assert.Equal($"reschedule_vote:{secondOptionId}", button.CallbackData);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+36
-18
@@ -5,32 +5,50 @@ namespace GmRelay.Bot.Tests.Features.Sessions.RescheduleSession;
|
||||
public sealed class RescheduleVoteRulesTests
|
||||
{
|
||||
[Fact]
|
||||
public void Evaluate_ShouldReject_WhenParticipantVotesNo()
|
||||
public void SelectWinner_ShouldApproveSingleTopOption()
|
||||
{
|
||||
var decision = RescheduleVoteRules.Evaluate("no", totalParticipants: 4, approvedParticipants: 3);
|
||||
var winningOptionId = Guid.NewGuid();
|
||||
var otherOptionId = Guid.NewGuid();
|
||||
|
||||
Assert.Equal(RescheduleVoteOutcome.Rejected, decision.Outcome);
|
||||
Assert.False(decision.ShouldRescheduleSession);
|
||||
Assert.Equal("Вы проголосовали против переноса.", decision.CallbackText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_ShouldApprove_WhenEveryoneVotedYes()
|
||||
{
|
||||
var decision = RescheduleVoteRules.Evaluate("yes", totalParticipants: 3, approvedParticipants: 3);
|
||||
var decision = RescheduleVoteRules.SelectWinner(
|
||||
[
|
||||
new RescheduleOptionVoteCount(winningOptionId, 3),
|
||||
new RescheduleOptionVoteCount(otherOptionId, 1)
|
||||
]);
|
||||
|
||||
Assert.Equal(RescheduleVoteOutcome.Approved, decision.Outcome);
|
||||
Assert.True(decision.ShouldRescheduleSession);
|
||||
Assert.True(decision.ShouldResetParticipantRsvps);
|
||||
Assert.Equal(winningOptionId, decision.SelectedOptionId);
|
||||
Assert.Equal("Победил вариант с большинством голосов.", decision.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_ShouldStayPending_WhileVotesOutstanding()
|
||||
public void SelectWinner_ShouldRejectTie()
|
||||
{
|
||||
var decision = RescheduleVoteRules.Evaluate("yes", totalParticipants: 5, approvedParticipants: 2);
|
||||
var firstOptionId = Guid.NewGuid();
|
||||
var secondOptionId = Guid.NewGuid();
|
||||
|
||||
Assert.Equal(RescheduleVoteOutcome.Pending, decision.Outcome);
|
||||
Assert.False(decision.ShouldRescheduleSession);
|
||||
Assert.False(decision.ShouldResetParticipantRsvps);
|
||||
var decision = RescheduleVoteRules.SelectWinner(
|
||||
[
|
||||
new RescheduleOptionVoteCount(firstOptionId, 2),
|
||||
new RescheduleOptionVoteCount(secondOptionId, 2)
|
||||
]);
|
||||
|
||||
Assert.Equal(RescheduleVoteOutcome.Rejected, decision.Outcome);
|
||||
Assert.Null(decision.SelectedOptionId);
|
||||
Assert.Equal("Голоса разделились поровну, перенос не применяется.", decision.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectWinner_ShouldRejectWhenNobodyVoted()
|
||||
{
|
||||
var decision = RescheduleVoteRules.SelectWinner(
|
||||
[
|
||||
new RescheduleOptionVoteCount(Guid.NewGuid(), 0),
|
||||
new RescheduleOptionVoteCount(Guid.NewGuid(), 0)
|
||||
]);
|
||||
|
||||
Assert.Equal(RescheduleVoteOutcome.Rejected, decision.Outcome);
|
||||
Assert.Null(decision.SelectedOptionId);
|
||||
Assert.Equal("Никто не проголосовал до дедлайна, перенос не применяется.", decision.Reason);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Telegram;
|
||||
|
||||
public sealed class TelegramMiniAppEntryPointTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task UpdateRouter_ShouldExposeMiniAppButtonInStartCommand()
|
||||
{
|
||||
var updateRouter = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs"));
|
||||
|
||||
Assert.Contains("Telegram:MiniAppUrl", updateRouter, StringComparison.Ordinal);
|
||||
Assert.Contains("InlineKeyboardButton.WithWebApp", updateRouter, StringComparison.Ordinal);
|
||||
Assert.Contains("Открыть dashboard", updateRouter, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BotStartup_ShouldRegisterMiniAppMenuButtonService()
|
||||
{
|
||||
var program = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Bot/Program.cs"));
|
||||
|
||||
Assert.Contains("TelegramMiniAppMenuButtonService", program, StringComparison.Ordinal);
|
||||
Assert.Contains("AddHostedService<TelegramMiniAppMenuButtonService>", program, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MiniAppMenuButtonService_ShouldSetTelegramWebAppMenuButtonWhenConfigured()
|
||||
{
|
||||
var service = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Bot/Infrastructure/Telegram/TelegramMiniAppMenuButtonService.cs"));
|
||||
|
||||
Assert.Contains("SetChatMenuButton", service, StringComparison.Ordinal);
|
||||
Assert.Contains("MenuButtonWebApp", service, StringComparison.Ordinal);
|
||||
Assert.Contains("Telegram:MiniAppUrl", service, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static string FindRepositoryFile(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Telegram;
|
||||
|
||||
public sealed class UpdateRouterTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetCommandText_ShouldUseCaption_WhenMessageHasNoText()
|
||||
{
|
||||
var message = new Message
|
||||
{
|
||||
Caption = """
|
||||
/newsession
|
||||
Название: Curse of Strahd
|
||||
"""
|
||||
};
|
||||
|
||||
var commandText = UpdateRouter.GetCommandText(message);
|
||||
|
||||
Assert.StartsWith("/newsession", commandText);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Rendering;
|
||||
|
||||
public sealed class SessionBatchRendererTests
|
||||
{
|
||||
[Fact]
|
||||
public void Render_ShouldOrderSessionsAndSkipButtonsForCancelledSessions()
|
||||
{
|
||||
var firstSessionId = Guid.NewGuid();
|
||||
var secondSessionId = Guid.NewGuid();
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(secondSessionId, new DateTime(2026, 4, 27, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 4),
|
||||
new SessionBatchDto(cancelledSessionId, new DateTime(2026, 4, 28, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Cancelled, null),
|
||||
new SessionBatchDto(firstSessionId, new DateTime(2026, 4, 26, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 2)
|
||||
};
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(secondSessionId, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(secondSessionId, "Charlie", null, ParticipantRegistrationStatus.Waitlisted),
|
||||
new ParticipantBatchDto(cancelledSessionId, "Bob", null, ParticipantRegistrationStatus.Active)
|
||||
};
|
||||
|
||||
var result = SessionBatchRenderer.Render("Campaign", sessions, participants);
|
||||
var text = result.Text;
|
||||
var buttons = result.Markup.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
|
||||
var firstIndex = text.IndexOf(sessions[2].ScheduledAt.FormatMoscow(), StringComparison.Ordinal);
|
||||
var secondIndex = text.IndexOf(sessions[0].ScheduledAt.FormatMoscow(), StringComparison.Ordinal);
|
||||
var thirdIndex = text.IndexOf(sessions[1].ScheduledAt.FormatMoscow(), StringComparison.Ordinal);
|
||||
|
||||
Assert.Contains("Campaign", text);
|
||||
Assert.True(firstIndex < secondIndex);
|
||||
Assert.True(secondIndex < thirdIndex);
|
||||
Assert.Contains("Места: 0/2", text);
|
||||
Assert.Contains("Места: 1/4", text);
|
||||
Assert.Contains("@alice", text);
|
||||
Assert.Contains("Лист ожидания (1)", text);
|
||||
Assert.Contains("Charlie", text);
|
||||
Assert.Contains("Bob", text);
|
||||
Assert.Equal(4, result.Markup.InlineKeyboard.Count());
|
||||
Assert.Collection(
|
||||
buttons.Select(button => button.CallbackData),
|
||||
callbackData => Assert.Equal($"join_session:{firstSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"leave_session:{firstSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"cancel_session:{firstSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"reschedule_session:{firstSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"join_session:{secondSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"leave_session:{secondSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"cancel_session:{secondSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"reschedule_session:{secondSessionId}", callbackData),
|
||||
callbackData => Assert.Equal($"promote_waitlist:{secondSessionId}", callbackData));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Rendering;
|
||||
|
||||
public sealed class SessionBatchViewBuilderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Build_ShouldOrderSessionsByDate()
|
||||
{
|
||||
var firstSessionId = Guid.NewGuid();
|
||||
var secondSessionId = Guid.NewGuid();
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(secondSessionId, new DateTime(2026, 4, 27, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 4),
|
||||
new SessionBatchDto(cancelledSessionId, new DateTime(2026, 4, 28, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Cancelled, null),
|
||||
new SessionBatchDto(firstSessionId, new DateTime(2026, 4, 26, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 2)
|
||||
};
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(secondSessionId, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(secondSessionId, "Charlie", null, ParticipantRegistrationStatus.Waitlisted),
|
||||
new ParticipantBatchDto(cancelledSessionId, "Bob", null, ParticipantRegistrationStatus.Active)
|
||||
};
|
||||
|
||||
var result = SessionBatchViewBuilder.Build("Campaign", sessions, participants);
|
||||
|
||||
Assert.Equal("Campaign", result.Title);
|
||||
Assert.Equal(3, result.Sessions.Count);
|
||||
Assert.Equal(firstSessionId, result.Sessions[0].SessionId);
|
||||
Assert.Equal(secondSessionId, result.Sessions[1].SessionId);
|
||||
Assert.Equal(cancelledSessionId, result.Sessions[2].SessionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ShouldCalculatePlayerCounts()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 4) };
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(sessionId, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(sessionId, "Bob", null, ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(sessionId, "Charlie", null, ParticipantRegistrationStatus.Waitlisted)
|
||||
};
|
||||
|
||||
var result = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var session = result.Sessions[0];
|
||||
|
||||
Assert.Equal(2, session.ActivePlayerCount);
|
||||
Assert.Equal(4, session.MaxPlayers);
|
||||
Assert.True(session.ActivePlayers.Count == 2);
|
||||
Assert.True(session.WaitlistedPlayers.Count == 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ShouldIncludeActionsForActiveSessions()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 4) };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var result = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var actions = result.Sessions[0].AvailableActions;
|
||||
|
||||
Assert.Equal(2, actions.Count);
|
||||
Assert.Equal("join_session", result.Sessions[0].AvailableActions[0].ActionKey);
|
||||
Assert.Equal("leave_session", result.Sessions[0].AvailableActions[1].ActionKey);
|
||||
Assert.Equal(sessionId, actions[0].SessionId);
|
||||
Assert.Equal(sessionId, actions[1].SessionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ShouldNotIncludeActionsForCancelledSessions()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Cancelled, null) };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var result = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
|
||||
Assert.Empty(result.Sessions[0].AvailableActions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ShouldMarkWaitlistActionWhenFull()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 1) };
|
||||
var participants = new[] { new ParticipantBatchDto(sessionId, "Alice", "alice", ParticipantRegistrationStatus.Active) };
|
||||
|
||||
var result = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var joinAction = result.Sessions[0].AvailableActions.First(a => a.ActionKey == "join_session");
|
||||
|
||||
Assert.Contains("ожидания", joinAction.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ShouldIncludePlayerUsernames()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, null) };
|
||||
var participants = new[] { new ParticipantBatchDto(sessionId, "Alice", "alice", ParticipantRegistrationStatus.Active) };
|
||||
|
||||
var result = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var player = result.Sessions[0].ActivePlayers[0];
|
||||
|
||||
Assert.Equal("Alice", player.DisplayName);
|
||||
Assert.Equal("alice", player.TelegramUsername);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Rendering;
|
||||
|
||||
public sealed class TelegramSessionBatchRendererTests
|
||||
{
|
||||
[Fact]
|
||||
public void Render_ShouldProduceCorrectHtmlAndButtons()
|
||||
{
|
||||
var firstSessionId = Guid.NewGuid();
|
||||
var secondSessionId = Guid.NewGuid();
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(secondSessionId, new DateTime(2026, 4, 27, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 4),
|
||||
new SessionBatchDto(cancelledSessionId, new DateTime(2026, 4, 28, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Cancelled, null),
|
||||
new SessionBatchDto(firstSessionId, new DateTime(2026, 4, 26, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 2)
|
||||
};
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(secondSessionId, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(secondSessionId, "Charlie", null, ParticipantRegistrationStatus.Waitlisted),
|
||||
new ParticipantBatchDto(cancelledSessionId, "Bob", null, ParticipantRegistrationStatus.Active)
|
||||
};
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Campaign", sessions, participants);
|
||||
var (text, markup) = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Contains("Campaign", text);
|
||||
Assert.Contains("@alice", text);
|
||||
Assert.Contains("Charlie", text);
|
||||
Assert.Contains("Bob", text);
|
||||
Assert.Contains("Сессия отменена", text);
|
||||
|
||||
var buttons = markup.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
Assert.Equal(4, buttons.Count); // 2 sessions x 2 buttons each
|
||||
|
||||
Assert.Contains(buttons, b => b.CallbackData == $"join_session:{firstSessionId}");
|
||||
Assert.Contains(buttons, b => b.CallbackData == $"leave_session:{firstSessionId}");
|
||||
Assert.Contains(buttons, b => b.CallbackData == $"join_session:{secondSessionId}");
|
||||
Assert.Contains(buttons, b => b.CallbackData == $"leave_session:{secondSessionId}");
|
||||
Assert.DoesNotContain(buttons, b => b.CallbackData?.StartsWith("cancel") == true);
|
||||
Assert.DoesNotContain(buttons, b => b.CallbackData?.StartsWith("reschedule") == true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldSkipButtonsForCancelledSessions()
|
||||
{
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(cancelledSessionId, DateTime.UtcNow, SessionStatus.Cancelled, null) };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (_, markup) = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Empty(markup.InlineKeyboard);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldShowWaitlistButtonWhenFull()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 1) };
|
||||
var participants = new[] { new ParticipantBatchDto(sessionId, "Alice", "alice", ParticipantRegistrationStatus.Active) };
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (_, markup) = TelegramSessionBatchRenderer.Render(view);
|
||||
var buttons = markup.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
var joinButton = buttons.First(b => b.CallbackData?.StartsWith("join_session:") == true);
|
||||
|
||||
Assert.Contains("ожидания", joinButton.Text);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using GmRelay.Web.Services;
|
||||
using GmRelay.Shared.Domain;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Web;
|
||||
|
||||
@@ -27,6 +28,34 @@ public sealed class AuthorizedSessionServiceTests
|
||||
Assert.Equal("Session A", sessions[0].Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUpcomingSessionsForGmAsync_ReturnsSessions_WhenUserIsCoGm()
|
||||
{
|
||||
var ownerId = 1001L;
|
||||
var coGmId = 2002L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", ownerId)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(Guid.NewGuid(), groupId, "Session A", DateTime.UtcNow, "Planned", "https://example.test/a", Guid.NewGuid(), 10, 42, 4, 1, 0)
|
||||
],
|
||||
managers:
|
||||
[
|
||||
new(groupId, coGmId, GroupManagerRole.CoGm)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
var sessions = await service.GetUpcomingSessionsForGmAsync(groupId, coGmId);
|
||||
|
||||
Assert.NotNull(sessions);
|
||||
Assert.Single(sessions);
|
||||
Assert.Equal("Session A", sessions[0].Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUpcomingSessionsForGmAsync_ReturnsNull_WhenGroupBelongsToAnotherGm()
|
||||
{
|
||||
@@ -138,6 +167,83 @@ public sealed class AuthorizedSessionServiceTests
|
||||
Assert.Equal(5, store.LastUpdatedMaxPlayers);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSessionForGmAsync_LogsAudit_WhenTitleChanges()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var sessionId = Guid.NewGuid();
|
||||
var originalTime = DateTime.UtcNow;
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(sessionId, groupId, "Session A", originalTime, "Planned", "https://example.test/a", Guid.NewGuid(), 10, 42, 4, 1, 0)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.UpdateSessionForGmAsync(sessionId, gmId, "Updated Title", originalTime, "https://example.test/a", 4);
|
||||
|
||||
Assert.Single(store.LogEntries);
|
||||
Assert.Equal("Title", store.LogEntries[0].ChangeType);
|
||||
Assert.Equal("Session A", store.LogEntries[0].OldValue);
|
||||
Assert.Equal("Updated Title", store.LogEntries[0].NewValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSessionForGmAsync_LogsMultipleAudits_WhenMultipleFieldsChange()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var sessionId = Guid.NewGuid();
|
||||
var originalTime = DateTime.UtcNow;
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(sessionId, groupId, "Session A", originalTime, "Planned", "https://example.test/a", Guid.NewGuid(), 10, 42, 4, 1, 0)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
var newTime = originalTime.AddDays(1);
|
||||
await service.UpdateSessionForGmAsync(sessionId, gmId, "Updated Title", newTime, "https://example.test/b", 5);
|
||||
|
||||
Assert.Equal(4, store.LogEntries.Count);
|
||||
Assert.Contains(store.LogEntries, e => e.ChangeType == "Title");
|
||||
Assert.Contains(store.LogEntries, e => e.ChangeType == "Time");
|
||||
Assert.Contains(store.LogEntries, e => e.ChangeType == "Link");
|
||||
Assert.Contains(store.LogEntries, e => e.ChangeType == "MaxPlayers");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSessionForGmAsync_DoesNotLogAudit_WhenNothingChanges()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var sessionId = Guid.NewGuid();
|
||||
var originalTime = DateTime.UtcNow;
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(sessionId, groupId, "Session A", originalTime, "Planned", "https://example.test/a", Guid.NewGuid(), 10, 42, 4, 1, 0)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.UpdateSessionForGmAsync(sessionId, gmId, "Session A", originalTime, "https://example.test/a", 4);
|
||||
|
||||
Assert.Empty(store.LogEntries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PromoteWaitlistedPlayerForGmAsync_PromotesOwnedSession()
|
||||
{
|
||||
@@ -210,6 +316,152 @@ public sealed class AuthorizedSessionServiceTests
|
||||
Assert.Equal("https://example.test/b", store.LastUpdatedBatchJoinLink);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBatchDetailsForGmAsync_UpdatesBatch_WhenUserIsCoGm()
|
||||
{
|
||||
var ownerId = 1001L;
|
||||
var coGmId = 2002L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var batchId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", ownerId)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(Guid.NewGuid(), groupId, "Session A", DateTime.UtcNow, "Planned", "https://example.test/a", batchId, 10, 42, 4, 1, 0)
|
||||
],
|
||||
managers:
|
||||
[
|
||||
new(groupId, coGmId, GroupManagerRole.CoGm)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.UpdateBatchDetailsForGmAsync(batchId, coGmId, "Updated", "https://example.test/b");
|
||||
|
||||
Assert.True(store.UpdateBatchDetailsCalled);
|
||||
Assert.Equal(batchId, store.LastUpdatedBatchId);
|
||||
Assert.Equal(groupId, store.LastUpdatedBatchGroupId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddCoGmForOwnerAsync_AddsCoGm_WhenUserIsOwner()
|
||||
{
|
||||
var ownerId = 1001L;
|
||||
var coGmId = 2002L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", ownerId)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.AddCoGmForOwnerAsync(groupId, ownerId, coGmId, "Assistant GM", "assistant");
|
||||
|
||||
Assert.True(store.AddCoGmCalled);
|
||||
Assert.Equal(groupId, store.LastAddedCoGmGroupId);
|
||||
Assert.Equal(coGmId, store.LastAddedCoGmTelegramId);
|
||||
Assert.Equal("Assistant GM", store.LastAddedCoGmDisplayName);
|
||||
Assert.Equal("assistant", store.LastAddedCoGmUsername);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddCoGmForOwnerAsync_Throws_WhenUserIsCoGm()
|
||||
{
|
||||
var ownerId = 1001L;
|
||||
var coGmId = 2002L;
|
||||
var newCoGmId = 3003L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", ownerId)
|
||||
],
|
||||
managers:
|
||||
[
|
||||
new(groupId, coGmId, GroupManagerRole.CoGm)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
var action = () => service.AddCoGmForOwnerAsync(groupId, coGmId, newCoGmId, "Second Assistant", null);
|
||||
|
||||
await Assert.ThrowsAsync<SessionAccessDeniedException>(action);
|
||||
Assert.False(store.AddCoGmCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveCoGmForOwnerAsync_RemovesCoGm_WhenUserIsOwner()
|
||||
{
|
||||
var ownerId = 1001L;
|
||||
var coGmId = 2002L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", ownerId)
|
||||
],
|
||||
managers:
|
||||
[
|
||||
new(groupId, coGmId, GroupManagerRole.CoGm)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.RemoveCoGmForOwnerAsync(groupId, ownerId, coGmId);
|
||||
|
||||
Assert.True(store.RemoveCoGmCalled);
|
||||
Assert.Equal(groupId, store.LastRemovedCoGmGroupId);
|
||||
Assert.Equal(coGmId, store.LastRemovedCoGmTelegramId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBatchNotificationModeForGmAsync_Throws_WhenBatchBelongsToAnotherGm()
|
||||
{
|
||||
var batchId = Guid.NewGuid();
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", 2002L)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(Guid.NewGuid(), groupId, "Session A", DateTime.UtcNow, "Planned", "https://example.test/a", batchId, 10, 42, 4, 1, 0)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
var action = () => service.UpdateBatchNotificationModeForGmAsync(batchId, 1001L, SessionNotificationMode.GroupOnly);
|
||||
|
||||
await Assert.ThrowsAsync<SessionAccessDeniedException>(action);
|
||||
Assert.False(store.UpdateBatchNotificationModeCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBatchNotificationModeForGmAsync_UpdatesOwnedBatch()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var batchId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
],
|
||||
sessions:
|
||||
[
|
||||
new(Guid.NewGuid(), groupId, "Session A", DateTime.UtcNow, "Planned", "https://example.test/a", batchId, 10, 42, 4, 1, 0)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.UpdateBatchNotificationModeForGmAsync(batchId, gmId, SessionNotificationMode.GroupOnly);
|
||||
|
||||
Assert.True(store.UpdateBatchNotificationModeCalled);
|
||||
Assert.Equal(batchId, store.LastUpdatedNotificationBatchId);
|
||||
Assert.Equal(groupId, store.LastUpdatedNotificationGroupId);
|
||||
Assert.Equal(SessionNotificationMode.GroupOnly, store.LastUpdatedNotificationMode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RescheduleBatchForGmAsync_RejectsNonPositiveInterval()
|
||||
{
|
||||
@@ -285,18 +537,166 @@ public sealed class AuthorizedSessionServiceTests
|
||||
Assert.Equal(BatchCloneInterval.NextWeek, store.LastCloneInterval);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateCampaignTemplateForGmAsync_CreatesTemplate_WhenGroupBelongsToGm()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.CreateCampaignTemplateForGmAsync(
|
||||
groupId,
|
||||
gmId,
|
||||
new CreateCampaignTemplateRequest(
|
||||
" Weekly arc ",
|
||||
" Kingmaker ",
|
||||
" https://example.test/kingmaker ",
|
||||
SessionCount: 6,
|
||||
IntervalDays: 7,
|
||||
MaxPlayers: 5,
|
||||
SessionNotificationMode.GroupOnly));
|
||||
|
||||
Assert.True(store.CreateCampaignTemplateCalled);
|
||||
Assert.Equal(groupId, store.LastCreatedCampaignTemplateGroupId);
|
||||
Assert.Equal("Weekly arc", store.LastCreatedCampaignTemplateRequest?.Name);
|
||||
Assert.Equal("Kingmaker", store.LastCreatedCampaignTemplateRequest?.Title);
|
||||
Assert.Equal("https://example.test/kingmaker", store.LastCreatedCampaignTemplateRequest?.JoinLink);
|
||||
Assert.Equal(6, store.LastCreatedCampaignTemplateRequest?.SessionCount);
|
||||
Assert.Equal(7, store.LastCreatedCampaignTemplateRequest?.IntervalDays);
|
||||
Assert.Equal(5, store.LastCreatedCampaignTemplateRequest?.MaxPlayers);
|
||||
Assert.Equal(SessionNotificationMode.GroupOnly, store.LastCreatedCampaignTemplateRequest?.NotificationMode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateCampaignTemplateForGmAsync_AllowsNoSeatLimit()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.CreateCampaignTemplateForGmAsync(
|
||||
groupId,
|
||||
gmId,
|
||||
new CreateCampaignTemplateRequest(
|
||||
"Open table",
|
||||
"West Marches",
|
||||
"https://example.test/west",
|
||||
8,
|
||||
7,
|
||||
null,
|
||||
SessionNotificationMode.GroupAndDirect));
|
||||
|
||||
Assert.True(store.CreateCampaignTemplateCalled);
|
||||
Assert.Null(store.LastCreatedCampaignTemplateRequest?.MaxPlayers);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateCampaignTemplateForGmAsync_Throws_WhenGroupBelongsToAnotherGm()
|
||||
{
|
||||
var groupId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", 2002L)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
var action = () => service.CreateCampaignTemplateForGmAsync(
|
||||
groupId,
|
||||
1001L,
|
||||
new CreateCampaignTemplateRequest(
|
||||
"Weekly arc",
|
||||
"Kingmaker",
|
||||
"https://example.test/kingmaker",
|
||||
SessionCount: 6,
|
||||
IntervalDays: 7,
|
||||
MaxPlayers: 5,
|
||||
SessionNotificationMode.GroupOnly));
|
||||
|
||||
await Assert.ThrowsAsync<SessionAccessDeniedException>(action);
|
||||
Assert.False(store.CreateCampaignTemplateCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateBatchFromCampaignTemplateForGmAsync_CreatesBatch_WhenTemplateGroupBelongsToGm()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var templateId = Guid.NewGuid();
|
||||
var firstScheduledAt = DateTime.UtcNow.AddDays(3);
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", gmId)
|
||||
],
|
||||
templates:
|
||||
[
|
||||
new(templateId, groupId, "Weekly arc", "Kingmaker", "https://example.test/kingmaker", 6, 7, 5, SessionNotificationModeExtensions.GroupOnlyValue, DateTime.UtcNow, DateTime.UtcNow)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.CreateBatchFromCampaignTemplateForGmAsync(templateId, gmId, firstScheduledAt);
|
||||
|
||||
Assert.True(store.CreateBatchFromTemplateCalled);
|
||||
Assert.Equal(templateId, store.LastCreatedBatchTemplateId);
|
||||
Assert.Equal(groupId, store.LastCreatedBatchTemplateGroupId);
|
||||
Assert.Equal(firstScheduledAt, store.LastCreatedBatchFirstScheduledAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateBatchFromCampaignTemplateForGmAsync_Throws_WhenTemplateGroupBelongsToAnotherGm()
|
||||
{
|
||||
var groupId = Guid.NewGuid();
|
||||
var templateId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups:
|
||||
[
|
||||
new(groupId, 42, "Alpha", 2002L)
|
||||
],
|
||||
templates:
|
||||
[
|
||||
new(templateId, groupId, "Weekly arc", "Kingmaker", "https://example.test/kingmaker", 6, 7, 5, SessionNotificationModeExtensions.GroupOnlyValue, DateTime.UtcNow, DateTime.UtcNow)
|
||||
]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
var action = () => service.CreateBatchFromCampaignTemplateForGmAsync(templateId, 1001L, DateTime.UtcNow.AddDays(3));
|
||||
|
||||
await Assert.ThrowsAsync<SessionAccessDeniedException>(action);
|
||||
Assert.False(store.CreateBatchFromTemplateCalled);
|
||||
}
|
||||
|
||||
private sealed class FakeSessionStore(
|
||||
IEnumerable<WebGameGroup>? groups = null,
|
||||
IEnumerable<WebSession>? sessions = null) : ISessionStore
|
||||
IEnumerable<WebSession>? sessions = null,
|
||||
IEnumerable<FakeGroupManager>? managers = null,
|
||||
IEnumerable<WebCampaignTemplate>? templates = null) : ISessionStore
|
||||
{
|
||||
private readonly Dictionary<Guid, WebGameGroup> groupsById = groups?.ToDictionary(group => group.Id) ?? [];
|
||||
private readonly Dictionary<Guid, WebSession> sessionsById = sessions?.ToDictionary(session => session.Id) ?? [];
|
||||
private readonly Dictionary<Guid, WebCampaignTemplate> templatesById = templates?.ToDictionary(template => template.Id) ?? [];
|
||||
private readonly List<FakeGroupManager> managers = managers?.ToList() ?? [];
|
||||
|
||||
public bool UpdateCalled { get; private set; }
|
||||
public bool PromoteCalled { get; private set; }
|
||||
public bool UpdateBatchDetailsCalled { get; private set; }
|
||||
public bool UpdateBatchNotificationModeCalled { get; private set; }
|
||||
public bool RescheduleBatchCalled { get; private set; }
|
||||
public bool CloneBatchCalled { get; private set; }
|
||||
public bool CreateCampaignTemplateCalled { get; private set; }
|
||||
public bool DeleteCampaignTemplateCalled { get; private set; }
|
||||
public bool CreateBatchFromTemplateCalled { get; private set; }
|
||||
public bool AddCoGmCalled { get; private set; }
|
||||
public bool RemoveCoGmCalled { get; private set; }
|
||||
public Guid? LastUpdatedSessionId { get; private set; }
|
||||
public Guid? LastUpdatedGroupId { get; private set; }
|
||||
public string? LastUpdatedTitle { get; private set; }
|
||||
@@ -309,6 +709,9 @@ public sealed class AuthorizedSessionServiceTests
|
||||
public Guid? LastUpdatedBatchGroupId { get; private set; }
|
||||
public string? LastUpdatedBatchTitle { get; private set; }
|
||||
public string? LastUpdatedBatchJoinLink { get; private set; }
|
||||
public Guid? LastUpdatedNotificationBatchId { get; private set; }
|
||||
public Guid? LastUpdatedNotificationGroupId { get; private set; }
|
||||
public SessionNotificationMode? LastUpdatedNotificationMode { get; private set; }
|
||||
public Guid? LastRescheduledBatchId { get; private set; }
|
||||
public Guid? LastRescheduledBatchGroupId { get; private set; }
|
||||
public DateTime? LastRescheduledFirstScheduledAt { get; private set; }
|
||||
@@ -316,9 +719,33 @@ public sealed class AuthorizedSessionServiceTests
|
||||
public Guid? LastClonedBatchId { get; private set; }
|
||||
public Guid? LastClonedBatchGroupId { get; private set; }
|
||||
public BatchCloneInterval? LastCloneInterval { get; private set; }
|
||||
public Guid? LastCreatedCampaignTemplateGroupId { get; private set; }
|
||||
public CreateCampaignTemplateRequest? LastCreatedCampaignTemplateRequest { get; private set; }
|
||||
public Guid? LastDeletedCampaignTemplateId { get; private set; }
|
||||
public Guid? LastDeletedCampaignTemplateGroupId { get; private set; }
|
||||
public Guid? LastCreatedBatchTemplateId { get; private set; }
|
||||
public Guid? LastCreatedBatchTemplateGroupId { get; private set; }
|
||||
public DateTime? LastCreatedBatchFirstScheduledAt { get; private set; }
|
||||
public Guid? LastAddedCoGmGroupId { get; private set; }
|
||||
public long? LastAddedCoGmTelegramId { get; private set; }
|
||||
public string? LastAddedCoGmDisplayName { get; private set; }
|
||||
public string? LastAddedCoGmUsername { get; private set; }
|
||||
public Guid? LastRemovedCoGmGroupId { get; private set; }
|
||||
public long? LastRemovedCoGmTelegramId { get; private set; }
|
||||
public bool RemovePlayerCalled { get; private set; }
|
||||
public Guid? LastRemovedPlayerSessionId { get; private set; }
|
||||
public Guid? LastRemovedPlayerGroupId { get; private set; }
|
||||
public Guid? LastRemovedPlayerParticipantId { get; private set; }
|
||||
public List<SessionAuditLogEntry> LogEntries { get; private set; } = new();
|
||||
public Guid? LastLogSessionId { get; private set; }
|
||||
public long? LastLogActorTelegramId { get; private set; }
|
||||
public string? LastLogActorName { get; private set; }
|
||||
public string? LastLogChangeType { get; private set; }
|
||||
public string? LastLogOldValue { get; private set; }
|
||||
public string? LastLogNewValue { get; private set; }
|
||||
|
||||
public Task<List<WebGameGroup>> GetGroupsForGmAsync(long gmId) =>
|
||||
Task.FromResult(groupsById.Values.Where(group => group.GmTelegramId == gmId).ToList());
|
||||
Task.FromResult(groupsById.Values.Where(group => IsManager(group.Id, gmId)).ToList());
|
||||
|
||||
public Task<WebGameGroup?> GetGroupAsync(Guid groupId)
|
||||
{
|
||||
@@ -326,6 +753,36 @@ public sealed class AuthorizedSessionServiceTests
|
||||
return Task.FromResult(group);
|
||||
}
|
||||
|
||||
public Task<bool> IsGroupManagerAsync(Guid groupId, long telegramId) =>
|
||||
Task.FromResult(IsManager(groupId, telegramId));
|
||||
|
||||
public Task<bool> IsGroupOwnerAsync(Guid groupId, long telegramId) =>
|
||||
Task.FromResult(IsOwner(groupId, telegramId));
|
||||
|
||||
public Task<List<WebGroupManager>> GetGroupManagersAsync(Guid groupId)
|
||||
{
|
||||
if (!groupsById.TryGetValue(groupId, out var group))
|
||||
{
|
||||
return Task.FromResult(new List<WebGroupManager>());
|
||||
}
|
||||
|
||||
var result = new List<WebGroupManager>
|
||||
{
|
||||
new(group.GmTelegramId, "Owner GM", null, GroupManagerRoleExtensions.OwnerValue, DateTime.UtcNow)
|
||||
};
|
||||
|
||||
result.AddRange(managers
|
||||
.Where(manager => manager.GroupId == groupId)
|
||||
.Select(manager => new WebGroupManager(
|
||||
manager.TelegramId,
|
||||
$"Co-GM {manager.TelegramId}",
|
||||
null,
|
||||
manager.Role.ToDatabaseValue(),
|
||||
DateTime.UtcNow)));
|
||||
|
||||
return Task.FromResult(result);
|
||||
}
|
||||
|
||||
public Task<List<WebSession>> GetUpcomingSessionsAsync(Guid groupId) =>
|
||||
Task.FromResult(sessionsById.Values.Where(session => session.GroupId == groupId).ToList());
|
||||
|
||||
@@ -388,6 +845,15 @@ public sealed class AuthorizedSessionServiceTests
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task UpdateBatchNotificationModeAsync(Guid batchId, Guid groupId, SessionNotificationMode notificationMode)
|
||||
{
|
||||
UpdateBatchNotificationModeCalled = true;
|
||||
LastUpdatedNotificationBatchId = batchId;
|
||||
LastUpdatedNotificationGroupId = groupId;
|
||||
LastUpdatedNotificationMode = notificationMode;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task RescheduleBatchAsync(Guid batchId, Guid groupId, DateTime firstScheduledAt, int intervalDays)
|
||||
{
|
||||
RescheduleBatchCalled = true;
|
||||
@@ -413,5 +879,123 @@ public sealed class AuthorizedSessionServiceTests
|
||||
DateTime.UtcNow.AddDays(7),
|
||||
1));
|
||||
}
|
||||
|
||||
public Task<List<WebCampaignTemplate>> GetCampaignTemplatesAsync(Guid groupId) =>
|
||||
Task.FromResult(templatesById.Values.Where(template => template.GroupId == groupId).ToList());
|
||||
|
||||
public Task<WebCampaignTemplate?> GetCampaignTemplateAsync(Guid templateId)
|
||||
{
|
||||
templatesById.TryGetValue(templateId, out var template);
|
||||
return Task.FromResult(template);
|
||||
}
|
||||
|
||||
public Task<WebCampaignTemplate> CreateCampaignTemplateAsync(Guid groupId, CreateCampaignTemplateRequest request)
|
||||
{
|
||||
CreateCampaignTemplateCalled = true;
|
||||
LastCreatedCampaignTemplateGroupId = groupId;
|
||||
LastCreatedCampaignTemplateRequest = request;
|
||||
|
||||
var template = new WebCampaignTemplate(
|
||||
Guid.NewGuid(),
|
||||
groupId,
|
||||
request.Name,
|
||||
request.Title,
|
||||
request.JoinLink,
|
||||
request.SessionCount,
|
||||
request.IntervalDays,
|
||||
request.MaxPlayers,
|
||||
request.NotificationMode.ToDatabaseValue(),
|
||||
DateTime.UtcNow,
|
||||
DateTime.UtcNow);
|
||||
|
||||
templatesById[template.Id] = template;
|
||||
return Task.FromResult(template);
|
||||
}
|
||||
|
||||
public Task DeleteCampaignTemplateAsync(Guid templateId, Guid groupId)
|
||||
{
|
||||
DeleteCampaignTemplateCalled = true;
|
||||
LastDeletedCampaignTemplateId = templateId;
|
||||
LastDeletedCampaignTemplateGroupId = groupId;
|
||||
templatesById.Remove(templateId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<WebSessionBatch> CreateBatchFromTemplateAsync(Guid templateId, Guid groupId, DateTime firstScheduledAt)
|
||||
{
|
||||
CreateBatchFromTemplateCalled = true;
|
||||
LastCreatedBatchTemplateId = templateId;
|
||||
LastCreatedBatchTemplateGroupId = groupId;
|
||||
LastCreatedBatchFirstScheduledAt = firstScheduledAt;
|
||||
|
||||
var template = templatesById[templateId];
|
||||
return Task.FromResult(new WebSessionBatch(
|
||||
Guid.NewGuid(),
|
||||
groupId,
|
||||
template.Title,
|
||||
template.JoinLink,
|
||||
firstScheduledAt,
|
||||
firstScheduledAt.AddDays(template.IntervalDays * (template.SessionCount - 1)),
|
||||
template.SessionCount,
|
||||
template.NotificationMode));
|
||||
}
|
||||
|
||||
public Task AddGroupCoGmAsync(Guid groupId, long ownerTelegramId, long coGmTelegramId, string displayName, string? telegramUsername)
|
||||
{
|
||||
AddCoGmCalled = true;
|
||||
LastAddedCoGmGroupId = groupId;
|
||||
LastAddedCoGmTelegramId = coGmTelegramId;
|
||||
LastAddedCoGmDisplayName = displayName;
|
||||
LastAddedCoGmUsername = telegramUsername;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task RemoveGroupCoGmAsync(Guid groupId, long coGmTelegramId)
|
||||
{
|
||||
RemoveCoGmCalled = true;
|
||||
LastRemovedCoGmGroupId = groupId;
|
||||
LastRemovedCoGmTelegramId = coGmTelegramId;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<List<WebParticipant>> GetSessionParticipantsAsync(Guid sessionId) =>
|
||||
Task.FromResult(new List<WebParticipant>());
|
||||
|
||||
public Task RemovePlayerFromSessionAsync(Guid sessionId, Guid groupId, Guid participantId)
|
||||
{
|
||||
RemovePlayerCalled = true;
|
||||
LastRemovedPlayerSessionId = sessionId;
|
||||
LastRemovedPlayerGroupId = groupId;
|
||||
LastRemovedPlayerParticipantId = participantId;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<List<PlayerAttendanceStats>> GetGroupAttendanceStatsAsync(Guid groupId) =>
|
||||
Task.FromResult(new List<PlayerAttendanceStats>());
|
||||
|
||||
public Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue)
|
||||
{
|
||||
var entry = new SessionAuditLogEntry(Guid.NewGuid(), sessionId, actorTelegramId, actorName, changeType, oldValue, newValue, DateTime.UtcNow);
|
||||
LogEntries.Add(entry);
|
||||
LastLogSessionId = sessionId;
|
||||
LastLogActorTelegramId = actorTelegramId;
|
||||
LastLogActorName = actorName;
|
||||
LastLogChangeType = changeType;
|
||||
LastLogOldValue = oldValue;
|
||||
LastLogNewValue = newValue;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId) =>
|
||||
Task.FromResult(LogEntries.Where(e => e.SessionId == sessionId).OrderByDescending(e => e.ChangedAt).ToList());
|
||||
|
||||
private bool IsManager(Guid groupId, long telegramId) =>
|
||||
IsOwner(groupId, telegramId) ||
|
||||
managers.Any(manager => manager.GroupId == groupId && manager.TelegramId == telegramId);
|
||||
|
||||
private bool IsOwner(Guid groupId, long telegramId) =>
|
||||
groupsById.TryGetValue(groupId, out var group) && group.GmTelegramId == telegramId;
|
||||
}
|
||||
|
||||
private sealed record FakeGroupManager(Guid GroupId, long TelegramId, GroupManagerRole Role);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,35 @@ public sealed class BatchSchedulePlannerTests
|
||||
Assert.Throws<ArgumentOutOfRangeException>(action);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRecurringSchedule_CreatesFixedIntervalScheduleFromFirstDate()
|
||||
{
|
||||
var firstScheduledAt = new DateTime(2026, 5, 4, 16, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var result = BatchSchedulePlanner.BuildRecurringSchedule(firstScheduledAt, sessionCount: 3, intervalDays: 14);
|
||||
|
||||
Assert.Equal(
|
||||
[
|
||||
firstScheduledAt,
|
||||
firstScheduledAt.AddDays(14),
|
||||
firstScheduledAt.AddDays(28)
|
||||
],
|
||||
result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 7)]
|
||||
[InlineData(53, 7)]
|
||||
[InlineData(3, 0)]
|
||||
public void BuildRecurringSchedule_RejectsInvalidTemplateShape(int sessionCount, int intervalDays)
|
||||
{
|
||||
var firstScheduledAt = new DateTime(2026, 5, 4, 16, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var action = () => BatchSchedulePlanner.BuildRecurringSchedule(firstScheduledAt, sessionCount, intervalDays);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(action);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(BatchCloneInterval.NextWeek, 2026, 5, 8)]
|
||||
[InlineData(BatchCloneInterval.NextMonth, 2026, 6, 1)]
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Web;
|
||||
|
||||
public sealed class CampaignTemplatesNavigationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task NavMenu_ShouldExposeTemplatesTab()
|
||||
{
|
||||
var navMenu = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Layout/NavMenu.razor"));
|
||||
|
||||
Assert.Contains("href=\"templates\"", navMenu, StringComparison.Ordinal);
|
||||
Assert.Contains("Шаблоны", navMenu, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NavMenu_ShouldExposeCurrentProjectVersion()
|
||||
{
|
||||
var navMenu = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Layout/NavMenu.razor"));
|
||||
var props = XDocument.Load(FindRepositoryFile("Directory.Build.props"));
|
||||
var version = props.Root?
|
||||
.Element("PropertyGroup")?
|
||||
.Element("Version")?
|
||||
.Value;
|
||||
|
||||
Assert.False(string.IsNullOrWhiteSpace(version));
|
||||
Assert.Contains($"v{version}", navMenu, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NavMenuStyles_ShouldStyleNavLinkAnchorsAsStackedRows()
|
||||
{
|
||||
var navCss = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Layout/NavMenu.razor.css"));
|
||||
|
||||
Assert.Contains("::deep .nav-item", navCss, StringComparison.Ordinal);
|
||||
Assert.Matches(
|
||||
@"\.nav-section\s*\{[^}]*display:\s*flex;[^}]*flex-direction:\s*column;[^}]*gap:\s*0\.25rem;",
|
||||
navCss);
|
||||
Assert.Matches(
|
||||
@"::deep\s+\.nav-item\s*\{[^}]*display:\s*flex;[^}]*width:\s*100%;",
|
||||
navCss);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GroupDetails_ShouldApplyTemplatesWithoutManagingThem()
|
||||
{
|
||||
var groupDetails = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Pages/GroupDetails.razor"));
|
||||
|
||||
Assert.Contains("CreateBatchFromTemplate", groupDetails, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("OnValidSubmit=\"CreateCampaignTemplate\"", groupDetails, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("DeleteCampaignTemplate", groupDetails, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CampaignTemplatesPage_ShouldOwnTemplateManagement()
|
||||
{
|
||||
var templatesPage = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Pages/CampaignTemplates.razor"));
|
||||
|
||||
Assert.Contains("@page \"/templates\"", templatesPage, StringComparison.Ordinal);
|
||||
Assert.Contains("OnValidSubmit=\"CreateCampaignTemplate\"", templatesPage, StringComparison.Ordinal);
|
||||
Assert.Contains("DeleteCampaignTemplate", templatesPage, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static string FindRepositoryFile(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
namespace GmRelay.Bot.Tests.Web;
|
||||
|
||||
public sealed class MiniAppDashboardTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task MiniAppPage_ShouldExposeTelegramWebAppDashboardEntryPoint()
|
||||
{
|
||||
var miniAppPage = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Pages/MiniApp.razor"));
|
||||
|
||||
Assert.Contains("@page \"/miniapp\"", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("authenticateTelegramMiniApp", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("/auth/telegram-webapp", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("watchTelegramMiniAppLogin", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("/auth/status", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("miniAppAuthStatus", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram-webapp-missing", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram-init-data-empty", miniAppPage, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram-auth-failed", miniAppPage, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppShell_ShouldLoadTelegramWebAppScriptAndAuthenticator()
|
||||
{
|
||||
var appShell = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/App.razor"));
|
||||
|
||||
Assert.Contains("telegram-web-app.js", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("window.authenticateTelegramMiniApp", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("Telegram.WebApp.initData", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("window.waitForTelegramMiniAppInitData", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("window.watchTelegramMiniAppLogin", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("window.handleTelegramLogin", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("/auth/telegram-login", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("data-onauth", appShell, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("data-auth-url", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("setTimeout(resolve, 100)", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("reloadOnReturn", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("gmRelayMiniAppLoginLeftPage", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("window.location.reload()", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("syncTelegramMiniAppViewport", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("safeAreaChanged", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("contentSafeAreaChanged", appShell, StringComparison.Ordinal);
|
||||
Assert.Contains("viewportChanged", appShell, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Program_ShouldMapTelegramWebAppAuthEndpoint()
|
||||
{
|
||||
var program = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Program.cs"));
|
||||
|
||||
Assert.Contains("MapPost(\"/auth/telegram-webapp\"", program, StringComparison.Ordinal);
|
||||
Assert.Contains("MapPost(\"/auth/telegram-login\"", program, StringComparison.Ordinal);
|
||||
Assert.Contains("VerifyWebAppInitData", program, StringComparison.Ordinal);
|
||||
Assert.Contains("VerifyLoginPayload", program, StringComparison.Ordinal);
|
||||
Assert.Contains("MapGet(\"/auth/status\"", program, StringComparison.Ordinal);
|
||||
Assert.Contains("authenticated", program, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Styles_ShouldIncludeMiniAppMobileDashboardRules()
|
||||
{
|
||||
var css = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/wwwroot/app.css"));
|
||||
|
||||
Assert.Contains("mini-app-page", css, StringComparison.Ordinal);
|
||||
Assert.Contains("mini-app-auth-card", css, StringComparison.Ordinal);
|
||||
Assert.Contains("@media (max-width: 768px)", css, StringComparison.Ordinal);
|
||||
Assert.Contains("--tg-safe-area-inset-top", css, StringComparison.Ordinal);
|
||||
Assert.Contains("--tg-content-safe-area-inset-top", css, StringComparison.Ordinal);
|
||||
Assert.Contains(".telegram-mini-app .nav-header", css, StringComparison.Ordinal);
|
||||
Assert.Contains(".telegram-mini-app .nav-toggle", css, StringComparison.Ordinal);
|
||||
Assert.Contains(".telegram-mini-app .mini-app-page", css, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoginPage_ShouldAuthenticateMiniAppFallbackInsideCurrentWebView()
|
||||
{
|
||||
var loginPage = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Pages/Login.razor"));
|
||||
|
||||
Assert.Contains(
|
||||
"JS.InvokeVoidAsync(\"loadTelegramWidget\", BotUsername, \"/auth/telegram-login\")",
|
||||
loginPage,
|
||||
StringComparison.Ordinal);
|
||||
Assert.Contains(
|
||||
"JS.InvokeVoidAsync(\"watchTelegramMiniAppLogin\", \"/auth/status\", \"/\", false)",
|
||||
loginPage,
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static string FindRepositoryFile(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GmRelay.Web.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -77,6 +78,183 @@ public sealed class TelegramAuthServiceTests
|
||||
Assert.False(verified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyWebAppInitData_ShouldAcceptValidTelegramWebAppPayload()
|
||||
{
|
||||
const string botToken = "test-bot-token";
|
||||
var initData = CreateWebAppInitData(
|
||||
botToken,
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["auth_date"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
|
||||
["query_id"] = "AAHdF6IQAAAAAN0XohDhrOrc",
|
||||
["user"] = """{"id":424242,"first_name":"Ada","last_name":"Lovelace","username":"ada"}"""
|
||||
});
|
||||
var service = new TelegramAuthService(CreateConfiguration(botToken));
|
||||
|
||||
var verified = service.VerifyWebAppInitData(initData, out var telegramId, out var name);
|
||||
|
||||
Assert.True(verified);
|
||||
Assert.Equal(424242L, telegramId);
|
||||
Assert.Equal("Ada Lovelace", name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyWebAppInitData_ShouldRejectTamperedHash()
|
||||
{
|
||||
const string botToken = "test-bot-token";
|
||||
var initData = CreateWebAppInitData(
|
||||
botToken,
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["auth_date"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
|
||||
["user"] = """{"id":424242,"first_name":"Ada"}"""
|
||||
});
|
||||
var tamperedInitData = initData.Replace("hash=", "hash=00", StringComparison.Ordinal);
|
||||
var service = new TelegramAuthService(CreateConfiguration(botToken));
|
||||
|
||||
var verified = service.VerifyWebAppInitData(tamperedInitData, out _, out _);
|
||||
|
||||
Assert.False(verified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyWebAppInitData_ShouldRejectExpiredPayload()
|
||||
{
|
||||
const string botToken = "test-bot-token";
|
||||
var initData = CreateWebAppInitData(
|
||||
botToken,
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["auth_date"] = DateTimeOffset.UtcNow.AddDays(-2).ToUnixTimeSeconds().ToString(),
|
||||
["user"] = """{"id":424242,"first_name":"Ada"}"""
|
||||
});
|
||||
var service = new TelegramAuthService(CreateConfiguration(botToken));
|
||||
|
||||
var verified = service.VerifyWebAppInitData(initData, out _, out _);
|
||||
|
||||
Assert.False(verified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyLoginPayload_ShouldAcceptValidTelegramWidgetCallbackPayload()
|
||||
{
|
||||
const string botToken = "test-bot-token";
|
||||
var authDate = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var values = new Dictionary<string, string>
|
||||
{
|
||||
["auth_date"] = authDate.ToString(),
|
||||
["first_name"] = "Ada",
|
||||
["id"] = "424242",
|
||||
["last_name"] = "Lovelace",
|
||||
["photo_url"] = "https://t.me/i/userpic/320/ada.jpg",
|
||||
["username"] = "ada"
|
||||
};
|
||||
var payload = new TelegramLoginPayload(
|
||||
424242,
|
||||
"Ada",
|
||||
"Lovelace",
|
||||
"ada",
|
||||
"https://t.me/i/userpic/320/ada.jpg",
|
||||
authDate,
|
||||
ComputeTelegramHash(botToken, values));
|
||||
var service = new TelegramAuthService(CreateConfiguration(botToken));
|
||||
|
||||
var verified = service.VerifyLoginPayload(payload, out var telegramId, out var name);
|
||||
|
||||
Assert.True(verified);
|
||||
Assert.Equal(424242L, telegramId);
|
||||
Assert.Equal("Ada Lovelace", name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyLoginPayload_ShouldRejectTamperedCallbackHash()
|
||||
{
|
||||
var payload = new TelegramLoginPayload(
|
||||
424242,
|
||||
"Ada",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
"00");
|
||||
var service = new TelegramAuthService(CreateConfiguration("test-bot-token"));
|
||||
|
||||
var verified = service.VerifyLoginPayload(payload, out _, out _);
|
||||
|
||||
Assert.False(verified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyLoginPayload_ShouldRejectExpiredCallbackPayload()
|
||||
{
|
||||
const string botToken = "test-bot-token";
|
||||
var authDate = DateTimeOffset.UtcNow.AddDays(-2).ToUnixTimeSeconds();
|
||||
var values = new Dictionary<string, string>
|
||||
{
|
||||
["auth_date"] = authDate.ToString(),
|
||||
["first_name"] = "Ada",
|
||||
["id"] = "424242"
|
||||
};
|
||||
var payload = new TelegramLoginPayload(
|
||||
424242,
|
||||
"Ada",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
authDate,
|
||||
ComputeTelegramHash(botToken, values));
|
||||
var service = new TelegramAuthService(CreateConfiguration(botToken));
|
||||
|
||||
var verified = service.VerifyLoginPayload(payload, out _, out _);
|
||||
|
||||
Assert.False(verified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyLoginPayload_ShouldRejectMissingRequiredCallbackFields()
|
||||
{
|
||||
var payload = new TelegramLoginPayload(
|
||||
0,
|
||||
"",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
"");
|
||||
var service = new TelegramAuthService(CreateConfiguration("test-bot-token"));
|
||||
|
||||
var verified = service.VerifyLoginPayload(payload, out _, out _);
|
||||
|
||||
Assert.False(verified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TelegramLoginPayload_ShouldDeserializeTelegramWidgetSnakeCaseJson()
|
||||
{
|
||||
var payload = JsonSerializer.Deserialize<TelegramLoginPayload>(
|
||||
"""
|
||||
{
|
||||
"id": 424242,
|
||||
"first_name": "Ada",
|
||||
"last_name": "Lovelace",
|
||||
"username": "ada",
|
||||
"photo_url": "https://t.me/i/userpic/320/ada.jpg",
|
||||
"auth_date": 1714300000,
|
||||
"hash": "abcdef"
|
||||
}
|
||||
""");
|
||||
|
||||
Assert.NotNull(payload);
|
||||
Assert.Equal(424242L, payload.Id);
|
||||
Assert.Equal("Ada", payload.FirstName);
|
||||
Assert.Equal("Lovelace", payload.LastName);
|
||||
Assert.Equal("ada", payload.Username);
|
||||
Assert.Equal("https://t.me/i/userpic/320/ada.jpg", payload.PhotoUrl);
|
||||
Assert.Equal(1714300000L, payload.AuthDate);
|
||||
Assert.Equal("abcdef", payload.Hash);
|
||||
}
|
||||
|
||||
private static IConfiguration CreateConfiguration(string botToken) =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
@@ -106,4 +284,27 @@ public sealed class TelegramAuthServiceTests
|
||||
var hashBytes = HMACSHA256.HashData(secretKey, Encoding.UTF8.GetBytes(dataCheckString));
|
||||
return Convert.ToHexString(hashBytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static string CreateWebAppInitData(string botToken, IReadOnlyDictionary<string, string> values)
|
||||
{
|
||||
var hash = ComputeTelegramWebAppHash(botToken, values);
|
||||
var encodedPairs = values
|
||||
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
|
||||
.Select(pair => $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value)}")
|
||||
.Append($"hash={hash}");
|
||||
|
||||
return string.Join("&", encodedPairs);
|
||||
}
|
||||
|
||||
private static string ComputeTelegramWebAppHash(string botToken, IReadOnlyDictionary<string, string> values)
|
||||
{
|
||||
var dataCheckString = string.Join(
|
||||
"\n",
|
||||
values
|
||||
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
|
||||
.Select(pair => $"{pair.Key}={pair.Value}"));
|
||||
var secretKey = HMACSHA256.HashData(Encoding.UTF8.GetBytes("WebAppData"), Encoding.UTF8.GetBytes(botToken));
|
||||
var hashBytes = HMACSHA256.HashData(secretKey, Encoding.UTF8.GetBytes(dataCheckString));
|
||||
return Convert.ToHexString(hashBytes).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
namespace GmRelay.Bot.Tests.Web;
|
||||
|
||||
public sealed class WebStylesTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AppCss_ShouldStyleNativeSelectOptionsForReadableDropdowns()
|
||||
{
|
||||
var css = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/wwwroot/app.css"));
|
||||
|
||||
Assert.Matches(
|
||||
@"select\s+option\s*\{[^}]*background:\s*var\(--bg-secondary\);[^}]*color:\s*var\(--text-primary\);",
|
||||
css);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppCss_ShouldReserveTelegramMiniAppSafeAreaForMobileChrome()
|
||||
{
|
||||
var appCss = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/wwwroot/app.css"));
|
||||
Assert.Contains("--gm-tg-safe-top", appCss, StringComparison.Ordinal);
|
||||
Assert.Contains("--tg-safe-area-inset-top", appCss, StringComparison.Ordinal);
|
||||
Assert.Contains("--tg-content-safe-area-inset-top", appCss, StringComparison.Ordinal);
|
||||
Assert.Contains("env(safe-area-inset-top", appCss, StringComparison.Ordinal);
|
||||
Assert.Contains(".telegram-mini-app .content", appCss, StringComparison.Ordinal);
|
||||
Assert.Contains(".telegram-mini-app .nav-header", appCss, StringComparison.Ordinal);
|
||||
Assert.Contains(".telegram-mini-app .nav-toggle", appCss, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppCss_ShouldKeepDesktopSessionActionsReadableWhenTableOverflows()
|
||||
{
|
||||
var appCss = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/wwwroot/app.css"));
|
||||
|
||||
Assert.Matches(
|
||||
@"\.session-table-desktop\s*\{[\s\S]*overflow-x:\s*auto;",
|
||||
appCss);
|
||||
Assert.Matches(
|
||||
@"\.session-table-desktop\s+\.gm-table\s*\{[\s\S]*min-width:\s*760px;",
|
||||
appCss);
|
||||
Assert.Matches(
|
||||
@"\.session-table-actions\s+\.btn-gm\s*\{[\s\S]*white-space:\s*nowrap;",
|
||||
appCss);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppCss_ShouldUseCardSessionLayoutInsideTelegramMiniApp()
|
||||
{
|
||||
var appCss = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/wwwroot/app.css"));
|
||||
|
||||
Assert.Matches(
|
||||
@"body\.telegram-mini-app\s+\.session-table-desktop\s*\{[\s\S]*display:\s*none;",
|
||||
appCss);
|
||||
Assert.Matches(
|
||||
@"body\.telegram-mini-app\s+\.session-card-mobile\s*\{[\s\S]*display:\s*block;",
|
||||
appCss);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppCss_ShouldUseCardSessionLayoutWhenDesktopSidebarLeavesNarrowContent()
|
||||
{
|
||||
var appCss = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/wwwroot/app.css"));
|
||||
|
||||
Assert.Matches(
|
||||
@"@media\s*\(max-width:\s*1024px\)\s*\{[\s\S]*\.session-table-desktop\s*\{[\s\S]*display:\s*none;[\s\S]*\.session-card-mobile\s*\{[\s\S]*display:\s*block;",
|
||||
appCss);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GroupDetailsPage_ShouldUseSessionTableLayoutClasses()
|
||||
{
|
||||
var groupDetailsPage = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Web/Components/Pages/GroupDetails.razor"));
|
||||
|
||||
Assert.Contains("session-table-desktop-card", groupDetailsPage, StringComparison.Ordinal);
|
||||
Assert.Contains("session-table-actions", groupDetailsPage, StringComparison.Ordinal);
|
||||
Assert.Contains("session-join-link", groupDetailsPage, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("overflow: hidden", groupDetailsPage, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static string FindRepositoryFile(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user