feat: wire email templates for outbound, welcome, and password reset flows
Enable template selection on admin single/bulk and scheduled emails, send welcome emails only after email registration OTP verification, and use the password_reset template for email-based reset links. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
b57b306372
commit
7836a9f95d
|
|
@ -144,6 +144,7 @@ func main() {
|
||||||
cfg,
|
cfg,
|
||||||
messengerSvc,
|
messengerSvc,
|
||||||
userSvc,
|
userSvc,
|
||||||
|
emailTemplateSvc,
|
||||||
)
|
)
|
||||||
|
|
||||||
recommendationRepo := repository.NewRecommendationRepository(store)
|
recommendationRepo := repository.NewRecommendationRepository(store)
|
||||||
|
|
|
||||||
3
db/migrations/000087_scheduled_email_templates.down.sql
Normal file
3
db/migrations/000087_scheduled_email_templates.down.sql
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
ALTER TABLE scheduled_notifications
|
||||||
|
DROP COLUMN IF EXISTS email_template_variables,
|
||||||
|
DROP COLUMN IF EXISTS email_template_slug;
|
||||||
3
db/migrations/000087_scheduled_email_templates.up.sql
Normal file
3
db/migrations/000087_scheduled_email_templates.up.sql
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
ALTER TABLE scheduled_notifications
|
||||||
|
ADD COLUMN IF NOT EXISTS email_template_slug VARCHAR(100),
|
||||||
|
ADD COLUMN IF NOT EXISTS email_template_variables JSONB;
|
||||||
|
|
@ -1,14 +1,16 @@
|
||||||
-- name: CreateScheduledNotification :one
|
-- name: CreateScheduledNotification :one
|
||||||
INSERT INTO scheduled_notifications (
|
INSERT INTO scheduled_notifications (
|
||||||
channel, title, message, html,
|
channel, title, message, html,
|
||||||
|
email_template_slug, email_template_variables,
|
||||||
scheduled_at,
|
scheduled_at,
|
||||||
target_user_ids, target_role, target_raw,
|
target_user_ids, target_role, target_raw,
|
||||||
created_by
|
created_by
|
||||||
) VALUES (
|
) VALUES (
|
||||||
$1, $2, $3, $4,
|
$1, $2, $3, $4,
|
||||||
$5,
|
$5, $6,
|
||||||
$6, $7, $8,
|
$7,
|
||||||
$9
|
$8, $9, $10,
|
||||||
|
$11
|
||||||
)
|
)
|
||||||
RETURNING *;
|
RETURNING *;
|
||||||
|
|
||||||
|
|
|
||||||
1224
docs/file-upload-admin-panel-integration.md
Normal file
1224
docs/file-upload-admin-panel-integration.md
Normal file
File diff suppressed because it is too large
Load Diff
|
|
@ -468,24 +468,26 @@ type RolePermission struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type ScheduledNotification struct {
|
type ScheduledNotification struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Channel string `json:"channel"`
|
Channel string `json:"channel"`
|
||||||
Title pgtype.Text `json:"title"`
|
Title pgtype.Text `json:"title"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Html pgtype.Text `json:"html"`
|
Html pgtype.Text `json:"html"`
|
||||||
ScheduledAt pgtype.Timestamptz `json:"scheduled_at"`
|
ScheduledAt pgtype.Timestamptz `json:"scheduled_at"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
TargetUserIds []int64 `json:"target_user_ids"`
|
TargetUserIds []int64 `json:"target_user_ids"`
|
||||||
TargetRole pgtype.Text `json:"target_role"`
|
TargetRole pgtype.Text `json:"target_role"`
|
||||||
TargetRaw []byte `json:"target_raw"`
|
TargetRaw []byte `json:"target_raw"`
|
||||||
AttemptCount int32 `json:"attempt_count"`
|
AttemptCount int32 `json:"attempt_count"`
|
||||||
LastError pgtype.Text `json:"last_error"`
|
LastError pgtype.Text `json:"last_error"`
|
||||||
ProcessingStartedAt pgtype.Timestamptz `json:"processing_started_at"`
|
ProcessingStartedAt pgtype.Timestamptz `json:"processing_started_at"`
|
||||||
SentAt pgtype.Timestamptz `json:"sent_at"`
|
SentAt pgtype.Timestamptz `json:"sent_at"`
|
||||||
CancelledAt pgtype.Timestamptz `json:"cancelled_at"`
|
CancelledAt pgtype.Timestamptz `json:"cancelled_at"`
|
||||||
CreatedBy int64 `json:"created_by"`
|
CreatedBy int64 `json:"created_by"`
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||||
|
EmailTemplateSlug pgtype.Text `json:"email_template_slug"`
|
||||||
|
EmailTemplateVariables []byte `json:"email_template_variables"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscriptionPlan struct {
|
type SubscriptionPlan struct {
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ SET
|
||||||
updated_at = CURRENT_TIMESTAMP
|
updated_at = CURRENT_TIMESTAMP
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
AND status IN ('pending', 'processing')
|
AND status IN ('pending', 'processing')
|
||||||
RETURNING id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at
|
RETURNING id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at, email_template_slug, email_template_variables
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) CancelScheduledNotification(ctx context.Context, id int64) (ScheduledNotification, error) {
|
func (q *Queries) CancelScheduledNotification(ctx context.Context, id int64) (ScheduledNotification, error) {
|
||||||
|
|
@ -44,6 +44,8 @@ func (q *Queries) CancelScheduledNotification(ctx context.Context, id int64) (Sc
|
||||||
&i.CreatedBy,
|
&i.CreatedBy,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
|
&i.EmailTemplateSlug,
|
||||||
|
&i.EmailTemplateVariables,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
@ -63,7 +65,7 @@ WHERE sn.id IN (
|
||||||
FOR UPDATE SKIP LOCKED
|
FOR UPDATE SKIP LOCKED
|
||||||
LIMIT $1
|
LIMIT $1
|
||||||
)
|
)
|
||||||
RETURNING id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at
|
RETURNING id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at, email_template_slug, email_template_variables
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) ClaimDueScheduledNotifications(ctx context.Context, limit int32) ([]ScheduledNotification, error) {
|
func (q *Queries) ClaimDueScheduledNotifications(ctx context.Context, limit int32) ([]ScheduledNotification, error) {
|
||||||
|
|
@ -94,6 +96,8 @@ func (q *Queries) ClaimDueScheduledNotifications(ctx context.Context, limit int3
|
||||||
&i.CreatedBy,
|
&i.CreatedBy,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
|
&i.EmailTemplateSlug,
|
||||||
|
&i.EmailTemplateVariables,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -137,28 +141,32 @@ func (q *Queries) CountScheduledNotifications(ctx context.Context, arg CountSche
|
||||||
const CreateScheduledNotification = `-- name: CreateScheduledNotification :one
|
const CreateScheduledNotification = `-- name: CreateScheduledNotification :one
|
||||||
INSERT INTO scheduled_notifications (
|
INSERT INTO scheduled_notifications (
|
||||||
channel, title, message, html,
|
channel, title, message, html,
|
||||||
|
email_template_slug, email_template_variables,
|
||||||
scheduled_at,
|
scheduled_at,
|
||||||
target_user_ids, target_role, target_raw,
|
target_user_ids, target_role, target_raw,
|
||||||
created_by
|
created_by
|
||||||
) VALUES (
|
) VALUES (
|
||||||
$1, $2, $3, $4,
|
$1, $2, $3, $4,
|
||||||
$5,
|
$5, $6,
|
||||||
$6, $7, $8,
|
$7,
|
||||||
$9
|
$8, $9, $10,
|
||||||
|
$11
|
||||||
)
|
)
|
||||||
RETURNING id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at
|
RETURNING id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at, email_template_slug, email_template_variables
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateScheduledNotificationParams struct {
|
type CreateScheduledNotificationParams struct {
|
||||||
Channel string `json:"channel"`
|
Channel string `json:"channel"`
|
||||||
Title pgtype.Text `json:"title"`
|
Title pgtype.Text `json:"title"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Html pgtype.Text `json:"html"`
|
Html pgtype.Text `json:"html"`
|
||||||
ScheduledAt pgtype.Timestamptz `json:"scheduled_at"`
|
EmailTemplateSlug pgtype.Text `json:"email_template_slug"`
|
||||||
TargetUserIds []int64 `json:"target_user_ids"`
|
EmailTemplateVariables []byte `json:"email_template_variables"`
|
||||||
TargetRole pgtype.Text `json:"target_role"`
|
ScheduledAt pgtype.Timestamptz `json:"scheduled_at"`
|
||||||
TargetRaw []byte `json:"target_raw"`
|
TargetUserIds []int64 `json:"target_user_ids"`
|
||||||
CreatedBy int64 `json:"created_by"`
|
TargetRole pgtype.Text `json:"target_role"`
|
||||||
|
TargetRaw []byte `json:"target_raw"`
|
||||||
|
CreatedBy int64 `json:"created_by"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) CreateScheduledNotification(ctx context.Context, arg CreateScheduledNotificationParams) (ScheduledNotification, error) {
|
func (q *Queries) CreateScheduledNotification(ctx context.Context, arg CreateScheduledNotificationParams) (ScheduledNotification, error) {
|
||||||
|
|
@ -167,6 +175,8 @@ func (q *Queries) CreateScheduledNotification(ctx context.Context, arg CreateSch
|
||||||
arg.Title,
|
arg.Title,
|
||||||
arg.Message,
|
arg.Message,
|
||||||
arg.Html,
|
arg.Html,
|
||||||
|
arg.EmailTemplateSlug,
|
||||||
|
arg.EmailTemplateVariables,
|
||||||
arg.ScheduledAt,
|
arg.ScheduledAt,
|
||||||
arg.TargetUserIds,
|
arg.TargetUserIds,
|
||||||
arg.TargetRole,
|
arg.TargetRole,
|
||||||
|
|
@ -193,12 +203,14 @@ func (q *Queries) CreateScheduledNotification(ctx context.Context, arg CreateSch
|
||||||
&i.CreatedBy,
|
&i.CreatedBy,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
|
&i.EmailTemplateSlug,
|
||||||
|
&i.EmailTemplateVariables,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const GetScheduledNotification = `-- name: GetScheduledNotification :one
|
const GetScheduledNotification = `-- name: GetScheduledNotification :one
|
||||||
SELECT id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at FROM scheduled_notifications
|
SELECT id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at, email_template_slug, email_template_variables FROM scheduled_notifications
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
|
|
@ -224,12 +236,14 @@ func (q *Queries) GetScheduledNotification(ctx context.Context, id int64) (Sched
|
||||||
&i.CreatedBy,
|
&i.CreatedBy,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
|
&i.EmailTemplateSlug,
|
||||||
|
&i.EmailTemplateVariables,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const ListScheduledNotifications = `-- name: ListScheduledNotifications :many
|
const ListScheduledNotifications = `-- name: ListScheduledNotifications :many
|
||||||
SELECT id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at
|
SELECT id, channel, title, message, html, scheduled_at, status, target_user_ids, target_role, target_raw, attempt_count, last_error, processing_started_at, sent_at, cancelled_at, created_by, created_at, updated_at, email_template_slug, email_template_variables
|
||||||
FROM scheduled_notifications
|
FROM scheduled_notifications
|
||||||
WHERE
|
WHERE
|
||||||
($1::text IS NULL OR status = $1)
|
($1::text IS NULL OR status = $1)
|
||||||
|
|
@ -284,6 +298,8 @@ func (q *Queries) ListScheduledNotifications(ctx context.Context, arg ListSchedu
|
||||||
&i.CreatedBy,
|
&i.CreatedBy,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
|
&i.EmailTemplateSlug,
|
||||||
|
&i.EmailTemplateVariables,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -139,6 +139,8 @@ type Config struct {
|
||||||
ResendSenderEmail string
|
ResendSenderEmail string
|
||||||
TeamInviteBaseURL string
|
TeamInviteBaseURL string
|
||||||
TeamInviteExpiry time.Duration
|
TeamInviteExpiry time.Duration
|
||||||
|
LearnerAppBaseURL string
|
||||||
|
PasswordResetBaseURL string
|
||||||
RedisAddr string
|
RedisAddr string
|
||||||
KafkaBrokers []string
|
KafkaBrokers []string
|
||||||
FCMServiceAccountKey string
|
FCMServiceAccountKey string
|
||||||
|
|
@ -494,6 +496,9 @@ func (c *Config) loadEnv() error {
|
||||||
}
|
}
|
||||||
c.TeamInviteExpiry = time.Duration(inviteExpiryHours) * time.Hour
|
c.TeamInviteExpiry = time.Duration(inviteExpiryHours) * time.Hour
|
||||||
|
|
||||||
|
c.LearnerAppBaseURL = strings.TrimRight(strings.TrimSpace(os.Getenv("LEARNER_APP_BASE_URL")), "/")
|
||||||
|
c.PasswordResetBaseURL = strings.TrimSpace(os.Getenv("PASSWORD_RESET_BASE_URL"))
|
||||||
|
|
||||||
c.FCMServiceAccountKey = strings.TrimSpace(os.Getenv("FCM_SERVICE_ACCOUNT_KEY"))
|
c.FCMServiceAccountKey = strings.TrimSpace(os.Getenv("FCM_SERVICE_ACCOUNT_KEY"))
|
||||||
if fp := strings.TrimSpace(os.Getenv("FCM_SERVICE_ACCOUNT_KEY_FILE")); fp != "" {
|
if fp := strings.TrimSpace(os.Getenv("FCM_SERVICE_ACCOUNT_KEY_FILE")); fp != "" {
|
||||||
raw, err := os.ReadFile(fp)
|
raw, err := os.ReadFile(fp)
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,8 @@ type LoginSuccess struct {
|
||||||
Role Role
|
Role Role
|
||||||
RfToken string
|
RfToken string
|
||||||
IsNewAccount bool
|
IsNewAccount bool
|
||||||
|
// WelcomeEmailEligible is true when a learner completed email-based registration OTP verification.
|
||||||
|
WelcomeEmailEligible bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoginRequest struct {
|
type LoginRequest struct {
|
||||||
|
|
|
||||||
12
internal/domain/outbound_email.go
Normal file
12
internal/domain/outbound_email.go
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
package domain
|
||||||
|
|
||||||
|
// OutboundEmailContent describes how to build an outbound email body.
|
||||||
|
// When TemplateSlug is set, the email is rendered from the matching email template.
|
||||||
|
// Otherwise Subject/Message/HTML are sent as-is (legacy free-form emails).
|
||||||
|
type OutboundEmailContent struct {
|
||||||
|
TemplateSlug string `json:"email_template_slug,omitempty"`
|
||||||
|
TemplateVariables map[string]any `json:"template_variables,omitempty"`
|
||||||
|
Subject string `json:"subject,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
HTML string `json:"html,omitempty"`
|
||||||
|
}
|
||||||
|
|
@ -30,6 +30,9 @@ type ScheduledNotification struct {
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
HTML string `json:"html,omitempty"`
|
HTML string `json:"html,omitempty"`
|
||||||
|
|
||||||
|
EmailTemplateSlug string `json:"email_template_slug,omitempty"`
|
||||||
|
EmailTemplateVariables json.RawMessage `json:"email_template_variables,omitempty"`
|
||||||
|
|
||||||
ScheduledAt time.Time `json:"scheduled_at"`
|
ScheduledAt time.Time `json:"scheduled_at"`
|
||||||
Status ScheduledNotificationStatus `json:"status"`
|
Status ScheduledNotificationStatus `json:"status"`
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,8 @@ func (r *Store) CreateScheduledNotification(
|
||||||
Title: pgtype.Text{String: sn.Title, Valid: sn.Title != ""},
|
Title: pgtype.Text{String: sn.Title, Valid: sn.Title != ""},
|
||||||
Message: sn.Message,
|
Message: sn.Message,
|
||||||
Html: pgtype.Text{String: sn.HTML, Valid: sn.HTML != ""},
|
Html: pgtype.Text{String: sn.HTML, Valid: sn.HTML != ""},
|
||||||
|
EmailTemplateSlug: pgtype.Text{String: sn.EmailTemplateSlug, Valid: sn.EmailTemplateSlug != ""},
|
||||||
|
EmailTemplateVariables: []byte(sn.EmailTemplateVariables),
|
||||||
ScheduledAt: pgtype.Timestamptz{Time: sn.ScheduledAt, Valid: true},
|
ScheduledAt: pgtype.Timestamptz{Time: sn.ScheduledAt, Valid: true},
|
||||||
TargetUserIds: sn.TargetUserIDs,
|
TargetUserIds: sn.TargetUserIDs,
|
||||||
TargetRole: pgtype.Text{String: sn.TargetRole, Valid: sn.TargetRole != ""},
|
TargetRole: pgtype.Text{String: sn.TargetRole, Valid: sn.TargetRole != ""},
|
||||||
|
|
@ -179,6 +181,12 @@ func mapScheduledDBToDomain(db *dbgen.ScheduledNotification) *domain.ScheduledNo
|
||||||
if db.Html.Valid {
|
if db.Html.Valid {
|
||||||
sn.HTML = db.Html.String
|
sn.HTML = db.Html.String
|
||||||
}
|
}
|
||||||
|
if db.EmailTemplateSlug.Valid {
|
||||||
|
sn.EmailTemplateSlug = db.EmailTemplateSlug.String
|
||||||
|
}
|
||||||
|
if len(db.EmailTemplateVariables) > 0 {
|
||||||
|
sn.EmailTemplateVariables = json.RawMessage(db.EmailTemplateVariables)
|
||||||
|
}
|
||||||
if db.TargetRole.Valid {
|
if db.TargetRole.Valid {
|
||||||
sn.TargetRole = db.TargetRole.String
|
sn.TargetRole = db.TargetRole.String
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -124,7 +124,8 @@ func (s *Service) VerifyOtp(
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Activate user if still pending
|
// 6. Activate user if still pending
|
||||||
if user.Status == domain.UserStatusPending {
|
wasPending := user.Status == domain.UserStatusPending
|
||||||
|
if wasPending {
|
||||||
if err := s.userStore.UpdateUserStatus(ctx, domain.UpdateUserStatusReq{
|
if err := s.userStore.UpdateUserStatus(ctx, domain.UpdateUserStatusReq{
|
||||||
UserID: user.ID,
|
UserID: user.ID,
|
||||||
Status: string(domain.UserStatusActive),
|
Status: string(domain.UserStatusActive),
|
||||||
|
|
@ -161,10 +162,15 @@ func (s *Service) VerifyOtp(
|
||||||
}
|
}
|
||||||
|
|
||||||
// 9. Return success payload
|
// 9. Return success payload
|
||||||
|
welcomeEmailEligible := wasPending &&
|
||||||
|
storedOtp.For == domain.OtpRegister &&
|
||||||
|
storedOtp.Medium == domain.OtpMediumEmail
|
||||||
|
|
||||||
return domain.LoginSuccess{
|
return domain.LoginSuccess{
|
||||||
UserId: user.ID,
|
UserId: user.ID,
|
||||||
Role: user.Role,
|
Role: user.Role,
|
||||||
RfToken: refreshToken,
|
RfToken: refreshToken,
|
||||||
|
WelcomeEmailEligible: welcomeEmailEligible,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
64
internal/services/emailtemplates/outbound.go
Normal file
64
internal/services/emailtemplates/outbound.go
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
package emailtemplates
|
||||||
|
|
||||||
|
import (
|
||||||
|
"Yimaru-Backend/internal/domain"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RenderOutbound builds subject/body from a template slug or returns legacy free-form content.
|
||||||
|
func (s *Service) RenderOutbound(ctx context.Context, content domain.OutboundEmailContent) (domain.RenderedEmail, error) {
|
||||||
|
slug := strings.TrimSpace(content.TemplateSlug)
|
||||||
|
if slug == "" {
|
||||||
|
subject := strings.TrimSpace(content.Subject)
|
||||||
|
message := strings.TrimSpace(content.Message)
|
||||||
|
html := strings.TrimSpace(content.HTML)
|
||||||
|
if subject == "" {
|
||||||
|
return domain.RenderedEmail{}, fmt.Errorf("subject is required when no email template is selected")
|
||||||
|
}
|
||||||
|
if message == "" && html == "" {
|
||||||
|
return domain.RenderedEmail{}, fmt.Errorf("message or html is required when no email template is selected")
|
||||||
|
}
|
||||||
|
if html == "" {
|
||||||
|
html = message
|
||||||
|
}
|
||||||
|
if message == "" {
|
||||||
|
message = html
|
||||||
|
}
|
||||||
|
return domain.RenderedEmail{
|
||||||
|
Subject: subject,
|
||||||
|
Text: message,
|
||||||
|
HTML: html,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
vars := cloneVariables(content.TemplateVariables)
|
||||||
|
if slug == domain.EmailTemplateSlugCustomMessage {
|
||||||
|
if subject := strings.TrimSpace(content.Subject); subject != "" {
|
||||||
|
vars["Subject"] = subject
|
||||||
|
}
|
||||||
|
if message := strings.TrimSpace(content.Message); message != "" {
|
||||||
|
vars["Message"] = message
|
||||||
|
}
|
||||||
|
if vars["Subject"] == nil || strings.TrimSpace(fmt.Sprint(vars["Subject"])) == "" {
|
||||||
|
return domain.RenderedEmail{}, fmt.Errorf("subject is required for custom_message template")
|
||||||
|
}
|
||||||
|
if vars["Message"] == nil || strings.TrimSpace(fmt.Sprint(vars["Message"])) == "" {
|
||||||
|
return domain.RenderedEmail{}, fmt.Errorf("message is required for custom_message template")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.Render(ctx, slug, vars)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneVariables(src map[string]any) map[string]any {
|
||||||
|
if len(src) == 0 {
|
||||||
|
return map[string]any{}
|
||||||
|
}
|
||||||
|
out := make(map[string]any, len(src))
|
||||||
|
for k, v := range src {
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"Yimaru-Backend/internal/domain"
|
"Yimaru-Backend/internal/domain"
|
||||||
"Yimaru-Backend/internal/pkgs/helpers"
|
"Yimaru-Backend/internal/pkgs/helpers"
|
||||||
"Yimaru-Backend/internal/ports"
|
"Yimaru-Backend/internal/ports"
|
||||||
|
"Yimaru-Backend/internal/services/emailtemplates"
|
||||||
"Yimaru-Backend/internal/services/messenger"
|
"Yimaru-Backend/internal/services/messenger"
|
||||||
"Yimaru-Backend/internal/services/user"
|
"Yimaru-Backend/internal/services/user"
|
||||||
"Yimaru-Backend/internal/web_server/ws"
|
"Yimaru-Backend/internal/web_server/ws"
|
||||||
|
|
@ -35,17 +36,18 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
store ports.NotificationStore
|
store ports.NotificationStore
|
||||||
Hub *ws.NotificationHub
|
Hub *ws.NotificationHub
|
||||||
connections sync.Map
|
connections sync.Map
|
||||||
notificationCh chan *domain.Notification
|
notificationCh chan *domain.Notification
|
||||||
stopCh chan struct{}
|
stopCh chan struct{}
|
||||||
config *config.Config
|
config *config.Config
|
||||||
userSvc *user.Service
|
userSvc *user.Service
|
||||||
messengerSvc *messenger.Service
|
messengerSvc *messenger.Service
|
||||||
mongoLogger *zap.Logger
|
emailTemplateSvc *emailtemplates.Service
|
||||||
logger *slog.Logger
|
mongoLogger *zap.Logger
|
||||||
fcmClient *messaging.Client
|
logger *slog.Logger
|
||||||
|
fcmClient *messaging.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(
|
func New(
|
||||||
|
|
@ -55,6 +57,7 @@ func New(
|
||||||
cfg *config.Config,
|
cfg *config.Config,
|
||||||
messengerSvc *messenger.Service,
|
messengerSvc *messenger.Service,
|
||||||
userSvc *user.Service,
|
userSvc *user.Service,
|
||||||
|
emailTemplateSvc *emailtemplates.Service,
|
||||||
) *Service {
|
) *Service {
|
||||||
hub := ws.NewNotificationHub()
|
hub := ws.NewNotificationHub()
|
||||||
|
|
||||||
|
|
@ -68,6 +71,7 @@ func New(
|
||||||
stopCh: make(chan struct{}),
|
stopCh: make(chan struct{}),
|
||||||
messengerSvc: messengerSvc,
|
messengerSvc: messengerSvc,
|
||||||
userSvc: userSvc,
|
userSvc: userSvc,
|
||||||
|
emailTemplateSvc: emailTemplateSvc,
|
||||||
config: cfg,
|
config: cfg,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -840,9 +844,17 @@ func (s *Service) SendBulkInAppNotification(
|
||||||
|
|
||||||
// SendBulkEmail sends an email to multiple recipients using the messenger service.
|
// SendBulkEmail sends an email to multiple recipients using the messenger service.
|
||||||
// It sends sequentially and returns the count of successful and failed deliveries.
|
// It sends sequentially and returns the count of successful and failed deliveries.
|
||||||
func (s *Service) SendBulkEmail(ctx context.Context, recipients []string, subject, message, messageHTML string, attachments []*resend.Attachment) (sent int, failed int) {
|
func (s *Service) SendBulkEmail(ctx context.Context, recipients []string, content domain.OutboundEmailContent, attachments []*resend.Attachment) (sent int, failed int) {
|
||||||
|
rendered, err := s.renderOutboundEmail(ctx, content)
|
||||||
|
if err != nil {
|
||||||
|
s.mongoLogger.Error("[NotificationSvc.SendBulkEmail] Failed to render email",
|
||||||
|
zap.Error(err),
|
||||||
|
)
|
||||||
|
return 0, len(recipients)
|
||||||
|
}
|
||||||
|
|
||||||
for _, email := range recipients {
|
for _, email := range recipients {
|
||||||
if err := s.messengerSvc.SendEmailWithAttachments(ctx, email, message, messageHTML, subject, attachments); err != nil {
|
if err := s.messengerSvc.SendEmailWithAttachments(ctx, email, rendered.Text, rendered.HTML, rendered.Subject, attachments); err != nil {
|
||||||
s.mongoLogger.Error("[NotificationSvc.SendBulkEmail] Failed to send email",
|
s.mongoLogger.Error("[NotificationSvc.SendBulkEmail] Failed to send email",
|
||||||
zap.String("email", email),
|
zap.String("email", email),
|
||||||
zap.Error(err),
|
zap.Error(err),
|
||||||
|
|
@ -862,6 +874,21 @@ func (s *Service) SendBulkEmail(ctx context.Context, recipients []string, subjec
|
||||||
return sent, failed
|
return sent, failed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) renderOutboundEmail(ctx context.Context, content domain.OutboundEmailContent) (domain.RenderedEmail, error) {
|
||||||
|
if s.emailTemplateSvc == nil {
|
||||||
|
return domain.RenderedEmail{}, fmt.Errorf("email template service is not configured")
|
||||||
|
}
|
||||||
|
return s.emailTemplateSvc.RenderOutbound(ctx, content)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SendOutboundEmail(ctx context.Context, recipient string, content domain.OutboundEmailContent, attachments []*resend.Attachment) error {
|
||||||
|
rendered, err := s.renderOutboundEmail(ctx, content)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.messengerSvc.SendEmailWithAttachments(ctx, recipient, rendered.Text, rendered.HTML, rendered.Subject, attachments)
|
||||||
|
}
|
||||||
|
|
||||||
// func (s *Service) startRetryWorker() {
|
// func (s *Service) startRetryWorker() {
|
||||||
// ticker := time.NewTicker(1 * time.Minute)
|
// ticker := time.NewTicker(1 * time.Minute)
|
||||||
// defer ticker.Stop()
|
// defer ticker.Stop()
|
||||||
|
|
@ -1262,7 +1289,22 @@ func (s *Service) dispatchScheduledEmail(ctx context.Context, sn *domain.Schedul
|
||||||
return fmt.Errorf("no email recipients resolved")
|
return fmt.Errorf("no email recipients resolved")
|
||||||
}
|
}
|
||||||
|
|
||||||
sent, failed := s.SendBulkEmail(ctx, emails, sn.Title, sn.Message, sn.HTML, nil)
|
var templateVars map[string]any
|
||||||
|
if len(sn.EmailTemplateVariables) > 0 {
|
||||||
|
if err := json.Unmarshal(sn.EmailTemplateVariables, &templateVars); err != nil {
|
||||||
|
return fmt.Errorf("invalid email_template_variables: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
content := domain.OutboundEmailContent{
|
||||||
|
TemplateSlug: sn.EmailTemplateSlug,
|
||||||
|
TemplateVariables: templateVars,
|
||||||
|
Subject: sn.Title,
|
||||||
|
Message: sn.Message,
|
||||||
|
HTML: sn.HTML,
|
||||||
|
}
|
||||||
|
|
||||||
|
sent, failed := s.SendBulkEmail(ctx, emails, content, nil)
|
||||||
if sent == 0 && failed > 0 {
|
if sent == 0 && failed > 0 {
|
||||||
return fmt.Errorf("all %d email deliveries failed", failed)
|
return fmt.Errorf("all %d email deliveries failed", failed)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,14 +10,6 @@ import (
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (s *Service) renderOtpMessage(ctx context.Context, otpCode, firstName string) (domain.RenderedEmail, error) {
|
|
||||||
return s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugOTP, map[string]any{
|
|
||||||
"OTP": otpCode,
|
|
||||||
"FirstName": firstName,
|
|
||||||
"ExpiresMinutes": int(OtpExpiry.Minutes()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) ResendOtp(
|
func (s *Service) ResendOtp(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
email, phone string,
|
email, phone string,
|
||||||
|
|
@ -35,7 +27,7 @@ func (s *Service) ResendOtp(
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
rendered, err := s.renderOtpMessage(ctx, otpCode, user.FirstName)
|
rendered, err := s.renderOtpMessage(ctx, otpCode, user.FirstName, otp.For, otp.Medium, otp.SentTo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -78,7 +70,7 @@ func (s *Service) SendOtp(ctx context.Context, userID int64, sentTo string, otpF
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
rendered, err := s.renderOtpMessage(ctx, otpCode, firstName)
|
rendered, err := s.renderOtpMessage(ctx, otpCode, firstName, otpFor, medium, sentTo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
89
internal/services/user/email_templates.go
Normal file
89
internal/services/user/email_templates.go
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"Yimaru-Backend/internal/domain"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Service) renderOtpMessage(ctx context.Context, otpCode, firstName string, otpFor domain.OtpFor, medium domain.OtpMedium, sentTo string) (domain.RenderedEmail, error) {
|
||||||
|
if otpFor == domain.OtpReset && medium == domain.OtpMediumEmail {
|
||||||
|
return s.renderPasswordResetEmail(ctx, otpCode, firstName, sentTo)
|
||||||
|
}
|
||||||
|
return s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugOTP, map[string]any{
|
||||||
|
"OTP": otpCode,
|
||||||
|
"FirstName": firstName,
|
||||||
|
"ExpiresMinutes": int(OtpExpiry.Minutes()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) renderPasswordResetEmail(ctx context.Context, otpCode, firstName, email string) (domain.RenderedEmail, error) {
|
||||||
|
resetLink := buildPasswordResetLink(s.config.PasswordResetBaseURL, s.config.LearnerAppBaseURL, email, otpCode)
|
||||||
|
return s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugPasswordReset, map[string]any{
|
||||||
|
"FirstName": firstName,
|
||||||
|
"ResetLink": resetLink,
|
||||||
|
"ExpiresMinutes": int(OtpExpiry.Minutes()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildPasswordResetLink(passwordResetBaseURL, learnerAppBaseURL, email, otp string) string {
|
||||||
|
base := strings.TrimRight(strings.TrimSpace(passwordResetBaseURL), "/")
|
||||||
|
if base == "" {
|
||||||
|
learnerBase := strings.TrimRight(strings.TrimSpace(learnerAppBaseURL), "/")
|
||||||
|
if learnerBase == "" {
|
||||||
|
learnerBase = "https://app.yimaruacademy.com"
|
||||||
|
}
|
||||||
|
base = learnerBase + "/reset-password"
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err := url.Parse(base)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("%s?email=%s&otp=%s", base, url.QueryEscape(email), url.QueryEscape(otp))
|
||||||
|
}
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("email", email)
|
||||||
|
q.Set("otp", otp)
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
return u.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) learnerLoginURL() string {
|
||||||
|
base := strings.TrimRight(strings.TrimSpace(s.config.LearnerAppBaseURL), "/")
|
||||||
|
if base == "" {
|
||||||
|
return "https://app.yimaruacademy.com/login"
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(base, "/login") {
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
return base + "/login"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RenderWelcomeEmail(ctx context.Context, firstName string) (domain.RenderedEmail, error) {
|
||||||
|
return s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugWelcome, map[string]any{
|
||||||
|
"FirstName": firstName,
|
||||||
|
"LoginURL": s.learnerLoginURL(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SendWelcomeEmail(ctx context.Context, userID int64) error {
|
||||||
|
if s.messengerSvc == nil || s.emailTemplateSvc == nil {
|
||||||
|
return fmt.Errorf("email services are not configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.userStore.GetUserByID(ctx, userID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(user.Email) == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rendered, err := s.RenderWelcomeEmail(ctx, user.FirstName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.messengerSvc.SendEmail(ctx, user.Email, rendered.Text, rendered.HTML, rendered.Subject)
|
||||||
|
}
|
||||||
|
|
@ -1658,31 +1658,28 @@ func (h *Handler) parseEmailAttachment(c *fiber.Ctx) []*resend.Attachment {
|
||||||
// @Failure 500 {object} domain.ErrorResponse
|
// @Failure 500 {object} domain.ErrorResponse
|
||||||
// @Router /api/v1/notifications/send-email [post]
|
// @Router /api/v1/notifications/send-email [post]
|
||||||
func (h *Handler) SendSingleEmail(c *fiber.Ctx) error {
|
func (h *Handler) SendSingleEmail(c *fiber.Ctx) error {
|
||||||
recipient := c.FormValue("recipient")
|
recipient := strings.TrimSpace(c.FormValue("recipient"))
|
||||||
subject := c.FormValue("subject")
|
|
||||||
message := c.FormValue("message")
|
|
||||||
html := c.FormValue("html")
|
|
||||||
|
|
||||||
if recipient == "" {
|
if recipient == "" {
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
Message: "Recipient is required",
|
Message: "Recipient is required",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if subject == "" {
|
|
||||||
|
content, err := parseOutboundEmailFromForm(c)
|
||||||
|
if err != nil {
|
||||||
|
if fe, ok := err.(*fiber.Error); ok {
|
||||||
|
return c.Status(fe.Code).JSON(domain.ErrorResponse{Message: fe.Message})
|
||||||
|
}
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
Message: "Subject is required",
|
Message: "Invalid email content",
|
||||||
})
|
Error: err.Error(),
|
||||||
}
|
|
||||||
if message == "" && html == "" {
|
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
||||||
Message: "Either message or html is required",
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
attachments := h.parseEmailAttachment(c)
|
attachments := h.parseEmailAttachment(c)
|
||||||
|
|
||||||
if err := h.notificationSvc.MessengerSvc().SendEmailWithAttachments(
|
if err := h.notificationSvc.SendOutboundEmail(
|
||||||
c.Context(), recipient, message, html, subject, attachments,
|
c.Context(), recipient, content, attachments,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
h.mongoLoggerSvc.Error("[NotificationHandler.SendSingleEmail] Failed to send email",
|
h.mongoLoggerSvc.Error("[NotificationHandler.SendSingleEmail] Failed to send email",
|
||||||
zap.String("recipient", recipient),
|
zap.String("recipient", recipient),
|
||||||
|
|
@ -1713,22 +1710,19 @@ func (h *Handler) SendSingleEmail(c *fiber.Ctx) error {
|
||||||
// @Failure 500 {object} domain.ErrorResponse
|
// @Failure 500 {object} domain.ErrorResponse
|
||||||
// @Router /api/v1/notifications/bulk-email [post]
|
// @Router /api/v1/notifications/bulk-email [post]
|
||||||
func (h *Handler) SendBulkEmail(c *fiber.Ctx) error {
|
func (h *Handler) SendBulkEmail(c *fiber.Ctx) error {
|
||||||
subject := c.FormValue("subject")
|
|
||||||
message := c.FormValue("message")
|
|
||||||
html := c.FormValue("html")
|
|
||||||
role := c.FormValue("role")
|
role := c.FormValue("role")
|
||||||
userIDsRaw := c.FormValue("user_ids")
|
userIDsRaw := c.FormValue("user_ids")
|
||||||
emailsRaw := c.FormValue("emails")
|
emailsRaw := c.FormValue("emails")
|
||||||
scheduledAtRaw := c.FormValue("scheduled_at")
|
scheduledAtRaw := c.FormValue("scheduled_at")
|
||||||
|
|
||||||
if subject == "" {
|
content, err := parseOutboundEmailFromForm(c)
|
||||||
|
if err != nil {
|
||||||
|
if fe, ok := err.(*fiber.Error); ok {
|
||||||
|
return c.Status(fe.Code).JSON(domain.ErrorResponse{Message: fe.Message})
|
||||||
|
}
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
Message: "Subject is required",
|
Message: "Invalid email content",
|
||||||
})
|
Error: err.Error(),
|
||||||
}
|
|
||||||
if message == "" && html == "" {
|
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
||||||
Message: "Either message or html is required",
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1785,15 +1779,17 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
sn := &domain.ScheduledNotification{
|
sn := &domain.ScheduledNotification{
|
||||||
Channel: domain.DeliveryChannelEmail,
|
Channel: domain.DeliveryChannelEmail,
|
||||||
Title: subject,
|
Title: content.Subject,
|
||||||
Message: message,
|
Message: content.Message,
|
||||||
HTML: html,
|
HTML: content.HTML,
|
||||||
ScheduledAt: scheduledAt,
|
EmailTemplateSlug: content.TemplateSlug,
|
||||||
TargetUserIDs: userIDs,
|
EmailTemplateVariables: outboundEmailTemplateVariablesJSON(content),
|
||||||
TargetRole: role,
|
ScheduledAt: scheduledAt,
|
||||||
TargetRaw: targetRaw,
|
TargetUserIDs: userIDs,
|
||||||
CreatedBy: creatorID,
|
TargetRole: role,
|
||||||
|
TargetRaw: targetRaw,
|
||||||
|
CreatedBy: creatorID,
|
||||||
}
|
}
|
||||||
|
|
||||||
created, err := h.notificationSvc.CreateScheduledNotification(c.Context(), sn)
|
created, err := h.notificationSvc.CreateScheduledNotification(c.Context(), sn)
|
||||||
|
|
@ -1859,11 +1855,11 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error {
|
||||||
|
|
||||||
attachments := h.parseEmailAttachment(c)
|
attachments := h.parseEmailAttachment(c)
|
||||||
|
|
||||||
sent, failed := h.notificationSvc.SendBulkEmail(c.Context(), recipients, subject, message, html, attachments)
|
sent, failed := h.notificationSvc.SendBulkEmail(c.Context(), recipients, content, attachments)
|
||||||
|
|
||||||
// Record in DB for history (only for known users)
|
// Record in DB for history (only for known users)
|
||||||
for _, uid := range userIDs {
|
for _, uid := range userIDs {
|
||||||
h.notificationSvc.RecordNotification(c.Context(), uid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelEmail, domain.NotificationLevelInfo, subject, message)
|
h.notificationSvc.RecordNotification(c.Context(), uid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelEmail, domain.NotificationLevelInfo, content.Subject, content.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkEmail] Bulk email sent",
|
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkEmail] Bulk email sent",
|
||||||
|
|
|
||||||
50
internal/web_server/handlers/outbound_email_form.go
Normal file
50
internal/web_server/handlers/outbound_email_form.go
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"Yimaru-Backend/internal/domain"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseOutboundEmailFromForm(c *fiber.Ctx) (domain.OutboundEmailContent, error) {
|
||||||
|
content := domain.OutboundEmailContent{
|
||||||
|
TemplateSlug: strings.TrimSpace(c.FormValue("email_template_slug")),
|
||||||
|
Subject: strings.TrimSpace(c.FormValue("subject")),
|
||||||
|
Message: strings.TrimSpace(c.FormValue("message")),
|
||||||
|
HTML: strings.TrimSpace(c.FormValue("html")),
|
||||||
|
}
|
||||||
|
|
||||||
|
varsRaw := strings.TrimSpace(c.FormValue("template_variables"))
|
||||||
|
if varsRaw != "" {
|
||||||
|
var vars map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(varsRaw), &vars); err != nil {
|
||||||
|
return domain.OutboundEmailContent{}, fiber.NewError(fiber.StatusBadRequest, "template_variables must be valid JSON")
|
||||||
|
}
|
||||||
|
content.TemplateVariables = vars
|
||||||
|
}
|
||||||
|
|
||||||
|
if content.TemplateSlug == "" {
|
||||||
|
if content.Subject == "" {
|
||||||
|
return domain.OutboundEmailContent{}, fiber.NewError(fiber.StatusBadRequest, "subject is required when no email_template_slug is provided")
|
||||||
|
}
|
||||||
|
if content.Message == "" && content.HTML == "" {
|
||||||
|
return domain.OutboundEmailContent{}, fiber.NewError(fiber.StatusBadRequest, "message or html is required when no email_template_slug is provided")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return content, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func outboundEmailTemplateVariablesJSON(content domain.OutboundEmailContent) json.RawMessage {
|
||||||
|
if len(content.TemplateVariables) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(content.TemplateVariables)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
@ -853,6 +853,18 @@ func (h *Handler) VerifyOtp(c *fiber.Ctx) error {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if loginSuccess.WelcomeEmailEligible {
|
||||||
|
if h.learnerNotifSvc != nil {
|
||||||
|
h.learnerNotifSvc.NotifyWelcome(loginSuccess.UserId)
|
||||||
|
}
|
||||||
|
if err := h.userSvc.SendWelcomeEmail(c.Context(), loginSuccess.UserId); err != nil {
|
||||||
|
h.mongoLoggerSvc.Warn("Failed to send welcome email",
|
||||||
|
zap.Int64("user_id", loginSuccess.UserId),
|
||||||
|
zap.Error(err),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
Message: "OTP verified successfully",
|
Message: "OTP verified successfully",
|
||||||
Data: loginUserRes{
|
Data: loginUserRes{
|
||||||
|
|
@ -1150,9 +1162,7 @@ func (h *Handler) RegisterUser(c *fiber.Ctx) error {
|
||||||
Error: err.Error(),
|
Error: err.Error(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if h.learnerNotifSvc != nil {
|
_ = created
|
||||||
h.learnerNotifSvc.NotifyWelcome(created.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
Message: "Registration successful",
|
Message: "Registration successful",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user