Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Add code to update the user entity on subscription update

Acho Arnoldce442d1a3ec4
diff --git a/api/pkg/entities/user.go b/api/pkg/entities/user.go
index 99225330..ae48d3a5 100644
--- a/api/pkg/entities/user.go
+++ b/api/pkg/entities/user.go
@@ -89,11 +89,21 @@ func (user User) IsOnProPlan() bool {
return user.SubscriptionName == SubscriptionNameProLifetime || user.SubscriptionName == SubscriptionNameProMonthly || user.SubscriptionName == SubscriptionNameProYearly
}
+// IsOnFreePlan checks if a user is on the free plan
+func (user User) IsOnFreePlan() bool {
+ return user.SubscriptionName == SubscriptionNameFree || user.SubscriptionName == ""
+}
+
// IsOnUltraPlan checks if a user is on the ultra plan
func (user User) IsOnUltraPlan() bool {
return user.SubscriptionName == SubscriptionNameUltraMonthly || user.SubscriptionName == SubscriptionNameUltraYearly
}
+// IsOn20kPlan checks if a user is on the 20k plan
+func (user User) IsOn20kPlan() bool {
+ return user.SubscriptionName == SubscriptionName20KMonthly || user.SubscriptionName == SubscriptionName20KYearly
+}
+
// UserTimeString converts the time to the user's timezone
func (user User) UserTimeString(timestamp time.Time) string {
location, err := time.LoadLocation(user.Timezone)
diff --git a/api/pkg/events/user_subscription_updated_event.go b/api/pkg/events/user_subscription_updated_event.go
new file mode 100644
index 00000000..90c4af9c
--- /dev/null
+++ b/api/pkg/events/user_subscription_updated_event.go
@@ -0,0 +1,21 @@
+package events
+
+import (
+ "time"
+
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+)
+
+// UserSubscriptionUpdated is raised when a user subscription is updated
+const UserSubscriptionUpdated = "user.subscription.updated"
+
+// UserSubscriptionUpdatedPayload stores the data for the UserSubscriptionUpdated event
+type UserSubscriptionUpdatedPayload struct {
+ UserID entities.UserID `json:"user_id"`
+ SubscriptionUpdatedAt time.Time `json:"subscription_updated_at"`
+ SubscriptionEndsAt time.Time `json:"subscription_ends_at"`
+ SubscriptionRenewsAt time.Time `json:"subscription_renews_at"`
+ SubscriptionID string `json:"subscription_id"`
+ SubscriptionName entities.SubscriptionName `json:"subscription_name"`
+ SubscriptionStatus string `json:"subscription_status"`
+}
diff --git a/api/pkg/handlers/lemonsqueezy_handler.go b/api/pkg/handlers/lemonsqueezy_handler.go
index d47af5a1..a6bfbb85 100644
--- a/api/pkg/handlers/lemonsqueezy_handler.go
+++ b/api/pkg/handlers/lemonsqueezy_handler.go
@@ -100,6 +100,13 @@ func (h *LemonsqueezyHandler) handleRequest(ctx context.Context, c *fiber.Ctx) e
return stacktrace.Propagate(err, fmt.Sprintf("cannot marshall [%s] to [%T]", c.Body(), request))
}
return h.service.HandleSubscriptionExpiredEvent(ctx, c.OriginalURL(), &request)
+ case "subscription_updated":
+ var request lemonsqueezy.WebhookRequestSubscription
+ err := json.Unmarshal(c.Body(), &request)
+ if err != nil {
+ return stacktrace.Propagate(err, fmt.Sprintf("cannot marshall [%s] to [%T]", c.Body(), request))
+ }
+ return h.service.HandleSubscriptionUpdatedEvent(ctx, c.OriginalURL(), &request)
default:
return stacktrace.NewError(fmt.Sprintf("invalid event [%s] received with request [%s]", eventName, c.Body()))
}
diff --git a/api/pkg/listeners/user_listener.go b/api/pkg/listeners/user_listener.go
index 06b1de8d..703578dd 100644
--- a/api/pkg/listeners/user_listener.go
+++ b/api/pkg/listeners/user_listener.go
@@ -36,6 +36,7 @@ func NewUserListener(
events.EventTypePhoneHeartbeatDead: l.onPhoneHeartbeatDead,
events.UserSubscriptionCreated: l.OnUserSubscriptionCreated,
events.UserSubscriptionCancelled: l.OnUserSubscriptionCancelled,
+ events.UserSubscriptionUpdated: l.OnUserSubscriptionUpdated,
events.UserSubscriptionExpired: l.OnUserSubscriptionExpired,
}
}
@@ -122,3 +123,22 @@ func (listener *UserListener) OnUserSubscriptionExpired(ctx context.Context, eve
return nil
}
+
+// OnUserSubscriptionUpdated handles the events.UserSubscriptionUpdated event
+func (listener *UserListener) OnUserSubscriptionUpdated(ctx context.Context, event cloudevents.Event) error {
+ ctx, span := listener.tracer.Start(ctx)
+ defer span.End()
+
+ var payload events.UserSubscriptionUpdatedPayload
+ if err := event.DataAs(&payload); err != nil {
+ msg := fmt.Sprintf("cannot decode [%s] into [%T]", event.Data(), payload)
+ return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ if err := listener.service.UpdateSubscription(ctx, &payload); err != nil {
+ msg := fmt.Sprintf("cannot expire subscription for user with ID [%s] for event with ID [%s]", payload.UserID, event.ID())
+ return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ return nil
+}
diff --git a/api/pkg/services/billing_service.go b/api/pkg/services/billing_service.go
index c9a19974..cbb3e5b5 100644
--- a/api/pkg/services/billing_service.go
+++ b/api/pkg/services/billing_service.go
@@ -207,7 +207,7 @@ func (service *BillingService) sendUsageAlert(ctx context.Context, userID entiti
}
func (service *BillingService) shouldSendAlert(user *entities.User, usage *entities.BillingUsage) bool {
- if !user.IsOnProPlan() && (usage.TotalMessages() == 160 || usage.TotalMessages() == 180 || usage.TotalMessages() == 190) {
+ if user.IsOnFreePlan() && (usage.TotalMessages() == 160 || usage.TotalMessages() == 180 || usage.TotalMessages() == 190) {
return true
}
@@ -219,5 +219,9 @@ func (service *BillingService) shouldSendAlert(user *entities.User, usage *entit
return true
}
+ if user.IsOn20kPlan() && (usage.TotalMessages() == 16000 || usage.TotalMessages() == 18000 || usage.TotalMessages() == 19000) {
+ return true
+ }
+
return false
}
diff --git a/api/pkg/services/lemonsqueezy_service.go b/api/pkg/services/lemonsqueezy_service.go
index 736dbdb6..300e5f5d 100644
--- a/api/pkg/services/lemonsqueezy_service.go
+++ b/api/pkg/services/lemonsqueezy_service.go
@@ -101,6 +101,41 @@ func (service *LemonsqueezyService) HandleSubscriptionCanceledEvent(ctx context.
return nil
}
+// HandleSubscriptionUpdatedEvent handles the subscription_cancelled lemonsqueezy event
+func (service *LemonsqueezyService) HandleSubscriptionUpdatedEvent(ctx context.Context, source string, request *lemonsqueezy.WebhookRequestSubscription) error {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ user, err := service.userRepository.LoadBySubscriptionID(ctx, request.Data.ID)
+ if err != nil {
+ msg := fmt.Sprintf("cannot load user with subscription ID [%s]", request.Data.ID)
+ return stacktrace.Propagate(err, msg)
+ }
+
+ payload := &events.UserSubscriptionUpdatedPayload{
+ UserID: user.ID,
+ SubscriptionUpdatedAt: request.Data.Attributes.UpdatedAt,
+ SubscriptionID: request.Data.ID,
+ SubscriptionName: service.subscriptionName(request.Data.Attributes.VariantName),
+ SubscriptionEndsAt: *request.Data.Attributes.EndsAt,
+ SubscriptionRenewsAt: request.Data.Attributes.RenewsAt,
+ SubscriptionStatus: request.Data.Attributes.Status,
+ }
+
+ event, err := service.createEvent(events.UserSubscriptionUpdated, source, payload)
+ if err != nil {
+ msg := fmt.Sprintf("cannot created [%s] event for user [%s]", events.UserSubscriptionUpdated, payload.UserID)
+ return stacktrace.Propagate(err, msg)
+ }
+
+ if err = service.eventDispatcher.Dispatch(ctx, event); err != nil {
+ msg := fmt.Sprintf("cannot dispatch [%s] event for user [%s]", event.Type(), payload.UserID)
+ return stacktrace.Propagate(err, msg)
+ }
+ ctxLogger.Info(fmt.Sprintf("[%s] subscription [%s] updated for user [%s]", payload.SubscriptionName, payload.SubscriptionID, payload.UserID))
+ return nil
+}
+
// HandleSubscriptionExpiredEvent handles the subscription_expired lemonsqueezy event
func (service *LemonsqueezyService) HandleSubscriptionExpiredEvent(ctx context.Context, source string, request *lemonsqueezy.WebhookRequestSubscription) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
diff --git a/api/pkg/services/user_service.go b/api/pkg/services/user_service.go
index 60a59507..4276434e 100644
--- a/api/pkg/services/user_service.go
+++ b/api/pkg/services/user_service.go
@@ -280,7 +280,7 @@ func (service *UserService) CancelSubscription(ctx context.Context, params *even
return nil
}
-// ExpireSubscription starts a subscription for an entities.User
+// ExpireSubscription finishes a subscription for an entities.User
func (service *UserService) ExpireSubscription(ctx context.Context, params *events.UserSubscriptionExpiredPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
@@ -304,3 +304,34 @@ func (service *UserService) ExpireSubscription(ctx context.Context, params *even
return nil
}
+
+// UpdateSubscription updates a subscription for an entities.User
+func (service *UserService) UpdateSubscription(ctx context.Context, params *events.UserSubscriptionUpdatedPayload) error {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ user, err := service.repository.Load(ctx, params.UserID)
+ if err != nil {
+ msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, params.UserID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ if params.SubscriptionStatus != "active" {
+ msg := fmt.Sprintf("subscription status is [%s] for [%T] with with ID [%s]", params.SubscriptionStatus, user, params.UserID)
+ ctxLogger.Info(msg)
+ return nil
+ }
+
+ user.SubscriptionID = &params.SubscriptionID
+ user.SubscriptionName = params.SubscriptionName
+ user.SubscriptionEndsAt = &params.SubscriptionEndsAt
+ user.SubscriptionRenewsAt = &params.SubscriptionRenewsAt
+ user.SubscriptionStatus = &params.SubscriptionStatus
+
+ if err = service.repository.Update(ctx, user); err != nil {
+ msg := fmt.Sprintf("could not update [%T] with with ID [%s] after subscription update", user, params.UserID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ return nil
+}