add email

This commit is contained in:
2026-09-17 23:34:03 +07:00
parent dfa4aa9d8b
commit 98f2fa91ac
7 changed files with 107 additions and 9 deletions
+1 -1
View File
@@ -143,7 +143,7 @@ MCP-эндпоинт: `http://localhost:8090/api/mcp`. ВНИМАНИЕ: REST-ga
`POST /api/games/{id}/registrations` — отдельный HTTP webhook, без пользовательского JWT. `POST /api/games/{id}/registrations` — отдельный HTTP webhook, без пользовательского JWT.
Капитан не должен иметь учётную запись. Создаётся обычная команда с автоматически Капитан не должен иметь учётную запись. Создаётся обычная команда с автоматически
сгенерированным паролем; почта капитана и количество участников видны организатору сгенерированным паролем; капитану отправляется письмо с данными регистрации, почта капитана и количество участников видны организатору
в списке команд игры. Письма автоматически не отправляются. в списке команд игры. Письма автоматически не отправляются.
Перед запуском примените миграции и задайте `YANDEX_FORMS_TOKEN` в окружении сервера Перед запуском примените миграции и задайте `YANDEX_FORMS_TOKEN` в окружении сервера
+1 -1
View File
@@ -148,7 +148,7 @@ func main() {
answerService := answer_service.NewAnswerService(gameRepo, teamRepo, scenarioService, answersRepo, actionsRepo) answerService := answer_service.NewAnswerService(gameRepo, teamRepo, scenarioService, answersRepo, actionsRepo)
teamService := team_service.NewTeamService(gameRepo, teamRepo, passwordGenerator, os.Getenv("APP_BASE_URL")) teamService := team_service.NewTeamService(gameRepo, teamRepo, passwordGenerator, os.Getenv("APP_BASE_URL"), emailSender)
participationService := participation_service.NewParticipationService(teamRepo, os.Getenv("APP_BASE_URL")) participationService := participation_service.NewParticipationService(teamRepo, os.Getenv("APP_BASE_URL"))
go participationService.RunParticipationEmails(context.Background(), emailSender, os.Getenv("PARTICIPATION_SECRET"), os.Getenv("GAME_TIMEZONE")) go participationService.RunParticipationEmails(context.Background(), emailSender, os.Getenv("PARTICIPATION_SECRET"), os.Getenv("GAME_TIMEZONE"))
+44
View File
@@ -0,0 +1,44 @@
package email_sender
import "html"
func ButtonHTML(link, label string) string {
return `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:20px 0;">
<tr><td class="email-button" bgcolor="#342a22" style="border-radius:5px; background-color:#342a22;">
<a href="` + html.EscapeString(link) + `" class="email-button-label" style="display:inline-block; padding:12px 20px; color:#ffffff; font-family:'font_old_typer','Courier New',serif; font-weight:400; text-decoration:none; font-size:18px; line-height:24px; border-radius:5px;">` + html.EscapeString(label) + `</a>
</td></tr></table>`
}
// WrapHTML is the shared light/dark email layout used by all service emails.
func WrapHTML(content, baseURL string) string {
fontURL := ""
if baseURL != "" {
fontURL = html.EscapeString(baseURL + "/email/a_OldTyper.ttf")
}
return `<!DOCTYPE html>
<html lang="ru"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark">
<style>
:root { color-scheme:light dark; supported-color-schemes:light dark; }
@font-face { font-family:'font_old_typer'; src:url('` + fontURL + `') format('truetype'); }
@media (prefers-color-scheme:dark) {
.email-page { background-color:#181818 !important; } .email-card { background-color:#262626 !important; }
.email-text, .email-text a { color:#f2ede6 !important; } .email-muted { color:#bdb5aa !important; }
.email-button { background-color:#dfc6a6 !important; } .email-button-label { color:#211a14 !important; }
}
[data-ogsb] .email-page, .email-page[data-ogsb] { background-color:#181818 !important; }
[data-ogsb] .email-card, .email-card[data-ogsb] { background-color:#262626 !important; }
[data-ogsc] .email-text, .email-text[data-ogsc], [data-ogsc] .email-text a { color:#f2ede6 !important; }
[data-ogsc] .email-muted, .email-muted[data-ogsc] { color:#bdb5aa !important; }
[data-ogsb] .email-button, .email-button[data-ogsb] { background-color:#dfc6a6 !important; }
[data-ogsc] .email-button-label, .email-button-label[data-ogsc] { color:#211a14 !important; }
</style></head>
<body class="email-page" style="margin:0; padding:0; background-color:#f3f0eb; font-family:Arial, Helvetica, sans-serif;">
<table class="email-page" role="presentation" width="100%" cellpadding="0" cellspacing="0" bgcolor="#f3f0eb" style="background-color:#f3f0eb; padding:24px 12px;"><tr><td align="center">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px; width:100%;">
<tr><td class="email-text" style="padding:16px 0 24px; color:#211a14;"><span style="font-family:'font_old_typer','Courier New',serif; font-size:22px; line-height:1.4; font-weight:normal;">ВЕЧЕРНИЙ ДЕТЕКТИВ</span></td></tr>
<tr><td class="email-card" bgcolor="#ffffff" style="padding:24px; background-color:#ffffff; border-radius:8px; font-family:'font_old_typer','Courier New',serif; font-size:18px; line-height:1.5; font-weight:400;">` + content + `</td></tr>
<tr><td class="email-muted" style="padding:24px 0; color:#655d54; font-size:12px; line-height:1.6;">Это автоматическое письмо сервиса «Вечерний детектив».<br>Если ты получил его по ошибке — просто ответь на это письмо.</td></tr>
</table></td></tr></table></body></html>`
}
@@ -68,7 +68,7 @@ func TestServicesLifecyclePostgres(t *testing.T) {
textCleaner := cleaner.NewCleaner() textCleaner := cleaner.NewCleaner()
scenarioService := scenarios_service.NewScenarioService(scenarios, textCleaner, "https://files.test/", nil, nil) scenarioService := scenarios_service.NewScenarioService(scenarios, textCleaner, "https://files.test/", nil, nil)
game := game_service.NewGameService(games, teams, scenarios, scenarioService, "https://files.test/", actions, applications) game := game_service.NewGameService(games, teams, scenarios, scenarioService, "https://files.test/", actions, applications)
team := team_service.NewTeamService(games, teams, password_generator.NewGenerator(12), "https://app.test") team := team_service.NewTeamService(games, teams, password_generator.NewGenerator(12), "https://app.test", nil)
play := gameplay_service.NewGameplayService(games, teams, scenarioService, storytelling.NewStory(textCleaner), actions, applications, textCleaner, "https://files.test/") play := gameplay_service.NewGameplayService(games, teams, scenarioService, storytelling.NewStory(textCleaner), actions, applications, textCleaner, "https://files.test/")
answers := answer_service.NewAnswerService(games, teams, scenarioService, team_answers_repo.NewTeamAnswersRepo(pool), actions) answers := answer_service.NewAnswerService(games, teams, scenarioService, team_answers_repo.NewTeamAnswersRepo(pool), actions)
participation := participation_service.NewParticipationService(teams, "https://app.test") participation := participation_service.NewParticipationService(teams, "https://app.test")
@@ -47,11 +47,12 @@ func participationEmail(p *teams_repo.Participation, baseURL, token string, loca
link := strings.TrimRight(baseURL, "/") + "/participation#token=" + token link := strings.TrimRight(baseURL, "/") + "/participation#token=" + token
date := p.StartAt.In(location).Format("02.01.2006 в 15:04 (MST, UTC-07:00)") date := p.StartAt.In(location).Format("02.01.2006 в 15:04 (MST, UTC-07:00)")
body := fmt.Sprintf("Команда «%s», подтвердите участие в игре «%s».\nДата: %s\nУчастников: %d\n\nПодтвердить участие: %s&answer=confirmed\nОтменить участие: %s&answer=cancelled\n\nОтвет можно дать до начала игры. Решение окончательное: изменить его нельзя. Без ответа запись сохраняется со статусом «Ожидает ответа».\nНе пересылайте письмо: ссылка позволяет принять решение за команду.", p.TeamName, p.GameName, date, p.ParticipantsCount, link, link) body := fmt.Sprintf("Команда «%s», подтвердите участие в игре «%s».\nДата: %s\nУчастников: %d\n\nПодтвердить участие: %s&answer=confirmed\nОтменить участие: %s&answer=cancelled\n\nОтвет можно дать до начала игры. Решение окончательное: изменить его нельзя. Без ответа запись сохраняется со статусом «Ожидает ответа».\nНе пересылайте письмо: ссылка позволяет принять решение за команду.", p.TeamName, p.GameName, date, p.ParticipantsCount, link, link)
markup := "<!doctype html><html lang=\"ru\"><meta charset=\"utf-8\"><body><h2>Подтвердите участие в игре</h2><p>" + html.EscapeString(p.TeamName) + " — «" + html.EscapeString(p.GameName) + "»</p><p>" + html.EscapeString(date) + fmt.Sprintf(" · Участников: %d</p>", p.ParticipantsCount) content := "<p class=\"email-text\"><strong>Подтвердите участие в игре</strong></p><p class=\"email-text\">" + html.EscapeString(p.TeamName) + " — «" + html.EscapeString(p.GameName) + "»</p><p class=\"email-text\">" + html.EscapeString(date) + fmt.Sprintf(" · Участников: %d</p>", p.ParticipantsCount)
for _, action := range []struct{ value, label string }{{"confirmed", "Подтвердить участие"}, {"cancelled", "Отменить участие"}} { for _, action := range []struct{ value, label string }{{"confirmed", "Подтвердить участие"}, {"cancelled", "Отменить участие"}} {
markup += `<p><a href="` + html.EscapeString(link+"&answer="+action.value) + `" style="display:inline-block;padding:12px 20px;background:#342a22;color:#fff;border-radius:5px">` + action.label + `</a></p>` content += email_sender.ButtonHTML(link+"&answer="+action.value, action.label)
} }
markup += "<p>Ответ можно дать до начала игры. <strong>Решение окончательное: изменить его нельзя.</strong></p><p>Без ответа запись сохраняется со статусом «Ожидает ответа».</p><p>Не пересылайте письмо: ссылка позволяет принять решение за команду.</p></body></html>" content += "<p class=\"email-text\">Ответ можно дать до начала игры. <strong>Решение окончательное: изменить его нельзя.</strong></p><p class=\"email-text\">Без ответа запись сохраняется со статусом «Ожидает ответа».</p><p class=\"email-text\">Не пересылайте письмо: ссылка позволяет принять решение за команду.</p>"
markup := email_sender.WrapHTML(content, strings.TrimRight(baseURL, "/"))
return email_sender.Message{To: p.Email, Subject: "Подтвердите участие в «Вечернем детективе»", Body: body, HTML: markup} return email_sender.Message{To: p.Email, Subject: "Подтвердите участие в «Вечернем детективе»", Body: body, HTML: markup}
} }
@@ -3,6 +3,8 @@ package team_service
import ( import (
"strings" "strings"
"testing" "testing"
"evening_detective_server/internal/repos"
) )
func TestRegistrationValidation(t *testing.T) { func TestRegistrationValidation(t *testing.T) {
@@ -30,3 +32,24 @@ func TestRegistrationValidation(t *testing.T) {
} }
} }
} }
func TestRegistrationEmail(t *testing.T) {
message := registrationEmail(&repos.Team{
ID: 7,
Name: "Команда",
CaptainEmail: "captain@example.org",
ParticipantsCount: 5,
Password: "abcdefgh",
}, "Большая игра", "https://app.test")
if message.To != "captain@example.org" {
t.Errorf("wrong recipient: %q", message.To)
}
for _, value := range []string{message.Body, message.HTML} {
if !strings.Contains(value, "Команда") || !strings.Contains(value, "abcdefgh") {
t.Errorf("registration email misses team data: %q", value)
}
}
if !strings.Contains(message.Body, "https://app.test/team-story/7?password=abcdefgh") {
t.Error("registration email misses team link")
}
}
+33 -3
View File
@@ -3,13 +3,18 @@ package team_service
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"html"
"strings"
"time"
"evening_detective_server/internal/modules/email_sender"
"evening_detective_server/internal/modules/game_model" "evening_detective_server/internal/modules/game_model"
"evening_detective_server/internal/modules/password_generator" "evening_detective_server/internal/modules/password_generator"
"evening_detective_server/internal/modules/team_qr_pdf" "evening_detective_server/internal/modules/team_qr_pdf"
"evening_detective_server/internal/repos"
"evening_detective_server/internal/repos/games_repo" "evening_detective_server/internal/repos/games_repo"
"evening_detective_server/internal/repos/teams_repo" "evening_detective_server/internal/repos/teams_repo"
"strings"
"time"
) )
type TeamService struct { type TeamService struct {
@@ -17,6 +22,7 @@ type TeamService struct {
teamsRepo *teams_repo.TeamsRepo teamsRepo *teams_repo.TeamsRepo
passwordGenerator password_generator.IPasswordGenerator passwordGenerator password_generator.IPasswordGenerator
appBaseURL string appBaseURL string
emailSender email_sender.IEmailSender
} }
func NewTeamService( func NewTeamService(
@@ -24,12 +30,14 @@ func NewTeamService(
teamsRepo *teams_repo.TeamsRepo, teamsRepo *teams_repo.TeamsRepo,
passwordGenerator password_generator.IPasswordGenerator, passwordGenerator password_generator.IPasswordGenerator,
appBaseURL string, appBaseURL string,
emailSender email_sender.IEmailSender,
) *TeamService { ) *TeamService {
return &TeamService{ return &TeamService{
gamesRepo: gamesRepo, gamesRepo: gamesRepo,
teamsRepo: teamsRepo, teamsRepo: teamsRepo,
passwordGenerator: passwordGenerator, passwordGenerator: passwordGenerator,
appBaseURL: appBaseURL, appBaseURL: appBaseURL,
emailSender: emailSender,
} }
} }
@@ -86,7 +94,29 @@ func (s *TeamService) RegisterTeam(ctx context.Context, gameID int, deliveryID s
return 0, err return 0, err
} }
autoConfirm := time.Now().Before(game.StartAt.Add(-24*time.Hour)) == false autoConfirm := time.Now().Before(game.StartAt.Add(-24*time.Hour)) == false
return s.teamsRepo.RegisterTeamWithParticipation(ctx, gameID, deliveryID, registration.Name, registration.Email, registration.ParticipantsCount, password, autoConfirm) id, err := s.teamsRepo.RegisterTeamWithParticipation(ctx, gameID, deliveryID, registration.Name, registration.Email, registration.ParticipantsCount, password, autoConfirm)
if err != nil {
return 0, err
}
if s.emailSender == nil {
return id, nil
}
team, err := s.teamsRepo.GetTeamByID(ctx, id)
if err != nil {
return 0, err
}
if err := s.emailSender.Send(ctx, registrationEmail(team, game.Name, s.appBaseURL)); err != nil {
return 0, fmt.Errorf("email send: %w", err)
}
return id, nil
}
func registrationEmail(team *repos.Team, gameName, baseURL string) email_sender.Message {
link := strings.TrimRight(baseURL, "/") + "/team-story/" + fmt.Sprint(team.ID) + "?password=" + team.Password
body := fmt.Sprintf("Регистрация команды «%s» в игре «%s» прошла успешно.\n\nУчастников: %d\nПароль команды: %s\n\nСсылка для входа в игру: %s\n\nСохраните это письмо и не пересылайте пароль посторонним.", team.Name, gameName, team.ParticipantsCount, team.Password, link)
content := fmt.Sprintf("<p class=\"email-text\">Регистрация команды <strong>%s</strong> в игре <strong>%s</strong> прошла успешно.</p><p class=\"email-text\">Участников: %d<br>Пароль команды: <strong>%s</strong></p>%s<p class=\"email-text\">Сохраните это письмо и не пересылайте пароль посторонним.</p>", html.EscapeString(team.Name), html.EscapeString(gameName), team.ParticipantsCount, html.EscapeString(team.Password), email_sender.ButtonHTML(link, "Войти в игру"))
markup := email_sender.WrapHTML(content, strings.TrimRight(baseURL, "/"))
return email_sender.Message{To: team.CaptainEmail, Subject: "Регистрация команды в «Вечернем детективе»", Body: body, HTML: markup}
} }
func (s *TeamService) DownloadTeamQR(ctx context.Context, id int) ([]byte, string, error) { func (s *TeamService) DownloadTeamQR(ctx context.Context, id int) ([]byte, string, error) {