feat: send subscription activated email on successful payment

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-02 05:49:25 -07:00
parent a52394825a
commit 8d46581485
12 changed files with 223 additions and 21 deletions

View File

@ -319,7 +319,7 @@ func main() {
store, // implements SubscriptionStore
)
learnerNotifSvc := learnernotificationsservice.New(notificationSvc)
learnerNotifSvc := learnernotificationsservice.New(notificationSvc, store, emailTemplateSvc, messengerSvc, cfg.LearnerAppBaseURL)
// Chapa service for subscription checkout payments
chapaSvc := chapa.NewService(

View File

@ -0,0 +1,2 @@
DELETE FROM email_templates
WHERE slug = 'subscription_activated';

View File

@ -0,0 +1,36 @@
INSERT INTO email_templates (slug, name, subject, body_text, body_html, variables, is_system, status)
VALUES (
'subscription_activated',
'Subscription Activated',
'Your Yimaru Academy subscription is active',
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
Your "{{.PlanName}}" {{.PackageLabel}} subscription is now active{{if .ExpiresLabel}} until {{.ExpiresLabel}}{{else if .IsLifetime}} with lifetime access{{end}}.
Sign in to start learning: {{.LoginURL}}',
$subscription_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Subscription active</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your <strong style="color:#9d2a83;">{{.PlanName}}</strong> {{.PackageLabel}} package is now active.{{if .IsLifetime}} You have lifetime access.{{else if .ExpiresLabel}} It is valid until <strong style="color:#333333;">{{.ExpiresLabel}}</strong>.{{end}}</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Start learning</a></p>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Thank you for subscribing to Yimaru Academy.</p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Yimaru Academy &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$subscription_html$,
'["FirstName", "PlanName", "PackageLabel", "LoginURL", "ExpiresLabel", "IsLifetime"]'::jsonb,
TRUE,
'ACTIVE'
)
ON CONFLICT (slug) DO NOTHING;

View File

@ -9,8 +9,9 @@ const (
EmailTemplateSlugOTP = "otp"
EmailTemplateSlugInvitation = "invitation"
EmailTemplateSlugPasswordReset = "password_reset"
EmailTemplateSlugWelcome = "welcome"
EmailTemplateSlugCustomMessage = "custom_message"
EmailTemplateSlugWelcome = "welcome"
EmailTemplateSlugSubscriptionActivated = "subscription_activated"
EmailTemplateSlugCustomMessage = "custom_message"
)
type EmailTemplate struct {

View File

@ -54,9 +54,9 @@ func (s *ArifpayService) SetLearnerNotifier(notifier *learnernotifications.Servi
s.learnerNotifier = notifier
}
func (s *ArifpayService) notifyLearnPackageSubscribed(userID int64, plan *domain.SubscriptionPlan) {
func (s *ArifpayService) notifyLearnPackageSubscribed(userID int64, plan *domain.SubscriptionPlan, expiresAt time.Time) {
if s.learnerNotifier != nil && plan != nil {
s.learnerNotifier.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name)
s.learnerNotifier.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name, expiresAt)
}
}
@ -292,7 +292,7 @@ func (s *ArifpayService) ProcessPaymentWebhook(ctx context.Context, req domain.W
if err := s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID); err != nil {
return fmt.Errorf("failed to link payment to subscription: %w", err)
}
s.notifyLearnPackageSubscribed(payment.UserID, plan)
s.notifyLearnPackageSubscribed(payment.UserID, plan, expiresAt)
}
return nil
@ -1048,7 +1048,7 @@ func (s *ArifpayService) VerifyDirectPaymentOTP(ctx context.Context, userID int6
})
if err == nil {
s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID)
s.notifyLearnPackageSubscribed(payment.UserID, plan)
s.notifyLearnPackageSubscribed(payment.UserID, plan, expiresAt)
}
}
}

View File

@ -373,7 +373,7 @@ func (s *Service) activateSubscription(ctx context.Context, payment *domain.Paym
}
if s.learnerNotifier != nil {
s.learnerNotifier.MaybeNotifyLearnPackageSubscribed(payment.UserID, plan.Category, plan.Name)
s.learnerNotifier.MaybeNotifyLearnPackageSubscribed(payment.UserID, plan.Category, plan.Name, expiresAt)
}
return nil

View File

@ -74,5 +74,14 @@ const (
defaultCustomMessageHTML = brandEmailHeader + `
<h1 style="` + brandHeadingStyle + `">{{.Subject}}</h1>
<div style="` + brandBodyStyle + `margin-bottom:0;">{{.Message}}</div>
` + brandEmailFooter
defaultSubscriptionActivatedSubject = "Your Yimaru Academy subscription is active"
defaultSubscriptionActivatedText = "Hi{{if .FirstName}} {{.FirstName}}{{end}},\n\nYour \"{{.PlanName}}\" {{.PackageLabel}} subscription is now active{{if .ExpiresLabel}} until {{.ExpiresLabel}}{{else if .IsLifetime}} with lifetime access{{end}}.\n\nSign in to start learning: {{.LoginURL}}"
defaultSubscriptionActivatedHTML = brandEmailHeader + `
<h1 style="` + brandHeadingStyle + `">Subscription active</h1>
<p style="` + brandBodyStyle + `">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your <strong style="color:#9d2a83;">{{.PlanName}}</strong> {{.PackageLabel}} package is now active.{{if .IsLifetime}} You have lifetime access.{{else if .ExpiresLabel}} It is valid until <strong style="color:#333333;">{{.ExpiresLabel}}</strong>.{{end}}</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="` + brandButtonPrimary + `">Start learning</a></p>
<p style="` + brandMutedStyle + `">Thank you for subscribing to Yimaru Academy.</p>
` + brandEmailFooter
)

View File

@ -51,6 +51,15 @@ var defaultTemplates = map[string]domain.EmailTemplate{
Variables: []string{"Subject", "Message"},
Status: domain.EmailTemplateStatusActive,
},
domain.EmailTemplateSlugSubscriptionActivated: {
Slug: domain.EmailTemplateSlugSubscriptionActivated,
Name: "Subscription Activated",
Subject: defaultSubscriptionActivatedSubject,
BodyText: defaultSubscriptionActivatedText,
BodyHTML: defaultSubscriptionActivatedHTML,
Variables: []string{"FirstName", "PlanName", "PackageLabel", "LoginURL", "ExpiresLabel", "IsLifetime"},
Status: domain.EmailTemplateStatusActive,
},
}
func defaultTemplate(slug string) (domain.EmailTemplate, bool) {

View File

@ -3,19 +3,39 @@ package learnernotifications
import (
"context"
"fmt"
"strings"
"time"
"Yimaru-Backend/internal/domain"
"Yimaru-Backend/internal/ports"
emailtemplates "Yimaru-Backend/internal/services/emailtemplates"
"Yimaru-Backend/internal/services/messenger"
notificationservice "Yimaru-Backend/internal/services/notification"
)
// Service sends learner-facing in-app and push notifications.
// Service sends learner-facing in-app, push, and email notifications.
type Service struct {
notifications *notificationservice.Service
notifications *notificationservice.Service
users ports.UserByID
emailTemplateSvc *emailtemplates.Service
messengerSvc *messenger.Service
learnerAppBaseURL string
}
func New(notifications *notificationservice.Service) *Service {
return &Service{notifications: notifications}
func New(
notifications *notificationservice.Service,
users ports.UserByID,
emailTemplateSvc *emailtemplates.Service,
messengerSvc *messenger.Service,
learnerAppBaseURL string,
) *Service {
return &Service{
notifications: notifications,
users: users,
emailTemplateSvc: emailTemplateSvc,
messengerSvc: messengerSvc,
learnerAppBaseURL: learnerAppBaseURL,
}
}
func (s *Service) NotifyWelcome(userID int64) {
@ -42,10 +62,19 @@ func (s *Service) NotifyProgramCompleted(userID int64, programName string) {
fmt.Sprintf("Amazing achievement! You completed the program \"%s\".", programName))
}
func (s *Service) NotifyLearnPackageSubscribed(userID int64, planName string) {
func (s *Service) NotifySubscriptionActivated(userID int64, planCategory, planName string, expiresAt time.Time) {
s.send(userID, domain.NOTIFICATION_TYPE_SUBSCRIPTION_ACTIVATED, domain.NotificationLevelSuccess,
"Subscription active",
fmt.Sprintf("Your \"%s\" Learn English package is now active. Enjoy your learning journey!", planName))
subscriptionActivatedMessage(planCategory, planName))
s.sendSubscriptionActivatedEmail(userID, planCategory, planName, expiresAt)
}
// MaybeNotifyLearnPackageSubscribed notifies learners when a paid subscription is activated.
func (s *Service) MaybeNotifyLearnPackageSubscribed(userID int64, planCategory, planName string, expiresAt time.Time) {
if strings.TrimSpace(planCategory) == "" || strings.TrimSpace(planName) == "" {
return
}
s.NotifySubscriptionActivated(userID, planCategory, planName, expiresAt)
}
func (s *Service) NotifyLearnPackageExpiringSoon(userID int64, planName string, expiresAt time.Time) {
@ -54,12 +83,6 @@ func (s *Service) NotifyLearnPackageExpiringSoon(userID int64, planName string,
fmt.Sprintf("Your \"%s\" package expires on %s. Renew to keep uninterrupted access.", planName, expiresAt.Format("Jan 2, 2006")))
}
func (s *Service) MaybeNotifyLearnPackageSubscribed(userID int64, planCategory, planName string) {
if planCategory == string(domain.SubscriptionCategoryLearnEnglish) {
s.NotifyLearnPackageSubscribed(userID, planName)
}
}
func (s *Service) NotifyLMSPracticeMilestones(userID int64, result domain.LMSPracticeCompletionResult) {
if result.ModuleCompleted != nil {
s.NotifyModuleCompleted(userID, result.ModuleCompleted.Name)
@ -106,3 +129,46 @@ func (s *Service) send(userID int64, notifType domain.NotificationType, level do
}
}()
}
func (s *Service) sendSubscriptionActivatedEmail(userID int64, planCategory, planName string, expiresAt time.Time) {
if s == nil || s.emailTemplateSvc == nil || s.messengerSvc == nil || s.users == nil || userID == 0 {
return
}
go func() {
ctx := context.Background()
user, err := s.users.GetUserByID(ctx, userID)
if err != nil {
return
}
email := strings.TrimSpace(user.Email)
if email == "" {
return
}
expiresLabel, isLifetime := subscriptionExpiresLabel(planCategory, expiresAt)
vars := map[string]any{
"FirstName": user.FirstName,
"PlanName": planName,
"PackageLabel": subscriptionPackageLabel(planCategory),
"LoginURL": s.learnerLoginURL(),
"ExpiresLabel": expiresLabel,
"IsLifetime": isLifetime,
}
rendered, err := s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugSubscriptionActivated, vars)
if err != nil {
return
}
_ = s.messengerSvc.SendEmail(ctx, email, rendered.Text, rendered.HTML, rendered.Subject)
}()
}
func (s *Service) learnerLoginURL() string {
base := strings.TrimRight(strings.TrimSpace(s.learnerAppBaseURL), "/")
if base == "" {
return "https://app.yimaruacademy.com/login"
}
if strings.HasSuffix(base, "/login") {
return base
}
return base + "/login"
}

View File

@ -0,0 +1,42 @@
package learnernotifications
import (
"strings"
"time"
"Yimaru-Backend/internal/domain"
)
func subscriptionPackageLabel(planCategory string) string {
switch strings.ToUpper(strings.TrimSpace(planCategory)) {
case string(domain.SubscriptionCategoryLearnEnglish):
return "Learn English"
case string(domain.SubscriptionCategoryIELTS):
return "IELTS"
case string(domain.SubscriptionCategoryDuolingo):
return "Duolingo"
default:
return "Yimaru Academy"
}
}
func subscriptionActivatedMessage(planCategory, planName string) string {
label := subscriptionPackageLabel(planCategory)
switch strings.ToUpper(strings.TrimSpace(planCategory)) {
case string(domain.SubscriptionCategoryLearnEnglish):
return "Your \"" + planName + "\" Learn English package is now active. Enjoy your learning journey!"
case string(domain.SubscriptionCategoryIELTS):
return "Your \"" + planName + "\" IELTS package is now active. Start preparing today!"
case string(domain.SubscriptionCategoryDuolingo):
return "Your \"" + planName + "\" Duolingo package is now active. Enjoy your learning journey!"
default:
return "Your \"" + planName + "\" " + label + " package is now active."
}
}
func subscriptionExpiresLabel(planCategory string, expiresAt time.Time) (expiresLabel string, isLifetime bool) {
if domain.IsLifetimeSubscriptionCategory(planCategory) {
return "", true
}
return expiresAt.Format("Jan 2, 2006"), false
}

View File

@ -0,0 +1,37 @@
package learnernotifications
import (
"testing"
"time"
"Yimaru-Backend/internal/domain"
)
func TestSubscriptionPackageLabel(t *testing.T) {
if got := subscriptionPackageLabel("IELTS"); got != "IELTS" {
t.Fatalf("got %q", got)
}
if got := subscriptionPackageLabel("learn_english"); got != "Learn English" {
t.Fatalf("got %q", got)
}
}
func TestSubscriptionExpiresLabel(t *testing.T) {
expiresAt := time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC)
label, lifetime := subscriptionExpiresLabel(string(domain.SubscriptionCategoryIELTS), expiresAt)
if lifetime || label != "Dec 31, 2026" {
t.Fatalf("label=%q lifetime=%v", label, lifetime)
}
label, lifetime = subscriptionExpiresLabel(string(domain.SubscriptionCategoryDuolingo), expiresAt)
if !lifetime || label != "" {
t.Fatalf("label=%q lifetime=%v", label, lifetime)
}
}
func TestSubscriptionActivatedMessage(t *testing.T) {
msg := subscriptionActivatedMessage(string(domain.SubscriptionCategoryIELTS), "Premium")
if msg == "" || msg == "Premium" {
t.Fatalf("unexpected message: %q", msg)
}
}

View File

@ -372,7 +372,7 @@ func (h *Handler) Subscribe(c *fiber.Ctx) error {
})
}
if h.learnerNotifSvc != nil {
h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name)
h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name, sub.ExpiresAt)
}
h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &sub.ID, fmt.Sprintf("Created subscription ID: %d", sub.ID), nil)