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
@@ -68,7 +68,7 @@ func TestServicesLifecyclePostgres(t *testing.T) {
textCleaner := cleaner.NewCleaner()
scenarioService := scenarios_service.NewScenarioService(scenarios, textCleaner, "https://files.test/", nil, nil)
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/")
answers := answer_service.NewAnswerService(games, teams, scenarioService, team_answers_repo.NewTeamAnswersRepo(pool), actions)
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
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)
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", "Отменить участие"}} {
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}
}
@@ -3,6 +3,8 @@ package team_service
import (
"strings"
"testing"
"evening_detective_server/internal/repos"
)
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 (
"context"
"errors"
"fmt"
"html"
"strings"
"time"
"evening_detective_server/internal/modules/email_sender"
"evening_detective_server/internal/modules/game_model"
"evening_detective_server/internal/modules/password_generator"
"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/teams_repo"
"strings"
"time"
)
type TeamService struct {
@@ -17,6 +22,7 @@ type TeamService struct {
teamsRepo *teams_repo.TeamsRepo
passwordGenerator password_generator.IPasswordGenerator
appBaseURL string
emailSender email_sender.IEmailSender
}
func NewTeamService(
@@ -24,12 +30,14 @@ func NewTeamService(
teamsRepo *teams_repo.TeamsRepo,
passwordGenerator password_generator.IPasswordGenerator,
appBaseURL string,
emailSender email_sender.IEmailSender,
) *TeamService {
return &TeamService{
gamesRepo: gamesRepo,
teamsRepo: teamsRepo,
passwordGenerator: passwordGenerator,
appBaseURL: appBaseURL,
emailSender: emailSender,
}
}
@@ -86,7 +94,29 @@ func (s *TeamService) RegisterTeam(ctx context.Context, gameID int, deliveryID s
return 0, err
}
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) {