Spaces:
Paused
Paused
File size: 20,898 Bytes
83a59ca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | package services
import (
"context"
"fmt"
"io"
"net/http"
"time"
"firebase.google.com/go/auth"
"github.com/NdoleStudio/httpsms/pkg/emails"
"github.com/NdoleStudio/httpsms/pkg/events"
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/lemonsqueezy-go"
"github.com/NdoleStudio/stacktrace"
"github.com/google/uuid"
"github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
)
// UserService is handles user requests
type UserService struct {
service
logger telemetry.Logger
tracer telemetry.Tracer
emailFactory emails.UserEmailFactory
mailer emails.Mailer
repository repositories.UserRepository
dispatcher *EventDispatcher
authClient *auth.Client
lemonsqueezyClient *lemonsqueezy.Client
httpClient *http.Client
}
// NewUserService creates a new UserService
func NewUserService(
logger telemetry.Logger,
tracer telemetry.Tracer,
repository repositories.UserRepository,
mailer emails.Mailer,
emailFactory emails.UserEmailFactory,
lemonsqueezyClient *lemonsqueezy.Client,
dispatcher *EventDispatcher,
authClient *auth.Client,
httpClient *http.Client,
) (s *UserService) {
return &UserService{
logger: logger.WithService(fmt.Sprintf("%T", s)),
tracer: tracer,
mailer: mailer,
emailFactory: emailFactory,
repository: repository,
dispatcher: dispatcher,
authClient: authClient,
lemonsqueezyClient: lemonsqueezyClient,
httpClient: httpClient,
}
}
// GetSubscriptionPayments fetches the subscription payments for an entities.User
func (service *UserService) GetSubscriptionPayments(ctx context.Context, userID entities.UserID) (invoices []lemonsqueezy.ApiResponseData[lemonsqueezy.SubscriptionInvoiceAttributes, lemonsqueezy.APIResponseRelationshipsSubscriptionInvoice], err error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
return invoices, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, userID))
}
if user.SubscriptionID == nil {
ctxLogger.Info(fmt.Sprintf("no subscription ID found for [%T] with ID [%s], returning empty invoices", user, user.ID))
return invoices, nil
}
ctxLogger.Info(fmt.Sprintf("fetching subscription payments for [%T] with ID [%s] and subscription [%s]", user, user.ID, *user.SubscriptionID))
invoicesResponse, _, err := service.lemonsqueezyClient.SubscriptionInvoices.List(ctx, map[string]string{"filter[subscription_id]": *user.SubscriptionID})
if err != nil {
return invoices, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get invoices for subscription [%s] for [%T] with with ID [%s]", *user.SubscriptionID, user, user.ID))
}
ctxLogger.Info(fmt.Sprintf("fetched [%d] payments for [%T] with ID [%s] and subscription ID [%s]", len(invoicesResponse.Data), user, user.ID, *user.SubscriptionID))
return invoicesResponse.Data, nil
}
// UserInvoiceGenerateParams are parameters for generating a subscription payment invoice
type UserInvoiceGenerateParams struct {
UserID entities.UserID
SubscriptionInvoiceID string
Name string
Address string
City string
State string
Country string
ZipCode string
Notes string
}
// GenerateReceipt generates a receipt for a subscription payment.
func (service *UserService) GenerateReceipt(ctx context.Context, params *UserInvoiceGenerateParams) (io.Reader, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
payload := map[string]string{
"name": params.Name,
"address": params.Address,
"city": params.City,
"state": params.State,
"country": params.Country,
"zip_code": params.ZipCode,
"notes": params.Notes,
"locale": "en",
}
invoice, _, err := service.lemonsqueezyClient.SubscriptionInvoices.Generate(ctx, params.SubscriptionInvoiceID, payload)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not generate subscription payment invoice user with ID [%s] and subscription invoice ID [%s]", params.UserID, params.SubscriptionInvoiceID))
}
response, err := service.httpClient.Get(invoice.Meta.Urls.DownloadInvoice)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not download subscription payment invoice for user with ID [%s] and subscription invoice ID [%s]", params.UserID, params.SubscriptionInvoiceID))
}
ctxLogger.Info(fmt.Sprintf("generated subscription payment invoice for user with ID [%s] and subscription invoice ID [%s]", params.UserID, params.SubscriptionInvoiceID))
return response.Body, nil
}
// Get fetches or creates an entities.User
func (service *UserService) Get(ctx context.Context, source string, authUser entities.AuthContext) (*entities.User, error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, isNew, err := service.repository.LoadOrStore(ctx, authUser)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with from [%+#v]", user, authUser))
}
if isNew {
service.dispatchUserCreatedEvent(ctx, source, user)
}
return user, nil
}
func (service *UserService) dispatchUserCreatedEvent(ctx context.Context, source string, user *entities.User) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
event, err := service.createEvent(events.UserAccountCreated, source, &events.UserAccountCreatedPayload{
UserID: user.ID,
Timestamp: time.Now().UTC(),
})
if err != nil {
ctxLogger.Error(stacktrace.Propagatef(err, "cannot create event [%s] for user [%s]", events.UserAccountCreated, user.ID))
return
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
ctxLogger.Error(stacktrace.Propagatef(err, "cannot dispatch [%s] event for user [%s]", event.Type(), user.ID))
return
}
}
// GetByID fetches an entities.User
func (service *UserService) GetByID(ctx context.Context, userID entities.UserID) (*entities.User, error) {
ctx, span, _ := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with ID [%s]", user, userID))
}
return user, nil
}
// UserUpdateParams are parameters for updating an entities.User
type UserUpdateParams struct {
Timezone *time.Location
ActivePhoneID *uuid.UUID
}
// Update an entities.User
func (service *UserService) Update(ctx context.Context, source string, authUser entities.AuthContext, params UserUpdateParams) (*entities.User, error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
user, isNew, err := service.repository.LoadOrStore(ctx, authUser)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with from [%+#v]", user, authUser))
}
if isNew {
service.dispatchUserCreatedEvent(ctx, source, user)
}
user.Timezone = params.Timezone.String()
user.ActivePhoneID = params.ActivePhoneID
if err = service.repository.Update(ctx, user); err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot save user with id [%s]", user.ID))
}
ctxLogger.Info(fmt.Sprintf("user saved with id [%s] in the userRepository", user.ID))
return user, nil
}
// UserNotificationUpdateParams are parameters for updating the notifications of a user
type UserNotificationUpdateParams struct {
MessageStatusEnabled bool
WebhookEnabled bool
HeartbeatEnabled bool
NewsletterEnabled bool
}
// UpdateNotificationSettings for an entities.User
func (service *UserService) UpdateNotificationSettings(ctx context.Context, userID entities.UserID, params *UserNotificationUpdateParams) (*entities.User, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not load [%T] with ID [%s]", user, userID))
}
user.NotificationWebhookEnabled = params.WebhookEnabled
user.NotificationHeartbeatEnabled = params.HeartbeatEnabled
user.NotificationMessageStatusEnabled = params.MessageStatusEnabled
user.NotificationNewsletterEnabled = params.NewsletterEnabled
if err = service.repository.Update(ctx, user); err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot save user with id [%s] in [%T]", user.ID, service.repository))
}
ctxLogger.Info(fmt.Sprintf("updated notification settings for [%T] with ID [%s] in the [%T]", user, user.ID, service.repository))
return user, nil
}
// RotateAPIKey for an entities.User
func (service *UserService) RotateAPIKey(ctx context.Context, source string, userID entities.UserID) (*entities.User, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.RotateAPIKey(ctx, userID)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not rotate API key for [%T] with ID [%s]", user, userID))
}
ctxLogger.Info(fmt.Sprintf("rotated the api key for [%T] with ID [%s] in the [%T]", user, user.ID, service.repository))
event, err := service.createEvent(events.UserAPIKeyRotated, source, &events.UserAPIKeyRotatedPayload{
UserID: user.ID,
Email: user.Email,
Timestamp: time.Now().UTC(),
Timezone: user.Timezone,
})
if err != nil {
ctxLogger.Error(stacktrace.Propagatef(err, "cannot create event [%s] for user [%s]", events.UserAPIKeyRotated, user.ID))
return user, nil
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
ctxLogger.Error(stacktrace.Propagatef(err, "cannot dispatch [%s] event for user [%s]", event.Type(), user.ID))
return user, nil
}
return user, nil
}
// Delete an entities.User
func (service *UserService) Delete(ctx context.Context, source string, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot load user with ID [%s] from the [%T]", userID, service.repository))
}
if !user.IsOnFreePlan() && user.SubscriptionRenewsAt != nil && user.SubscriptionRenewsAt.After(time.Now()) {
return service.tracer.WrapErrorSpan(span, stacktrace.NewErrorf("cannot delete user with ID [%s] because they are have an active [%s] subscription which renews at [%s]", userID, user.SubscriptionName, user.SubscriptionRenewsAt))
}
if err = service.repository.Delete(ctx, user); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not delete user with ID [%s] from the [%T]", userID, service.repository))
}
ctxLogger.Info(fmt.Sprintf("sucessfully deleted user with ID [%s] in the [%T]", userID, service.repository))
event, err := service.createEvent(events.UserAccountDeleted, source, &events.UserAccountDeletedPayload{
UserID: userID,
UserEmail: user.Email,
Timestamp: time.Now().UTC(),
})
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create event [%s] for user [%s]", events.UserAccountDeleted, userID))
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot dispatch [%s] event for user [%s]", event.Type(), userID))
}
return nil
}
// SendAPIKeyRotatedEmail sends an email to an entities.User when the API key is rotated
func (service *UserService) SendAPIKeyRotatedEmail(ctx context.Context, payload *events.UserAPIKeyRotatedPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
email, err := service.emailFactory.APIKeyRotated(payload.Email, payload.Timestamp, payload.Timezone)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create api key rotated email for user [%s]", payload.UserID))
}
if err = service.mailer.Send(ctx, email); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "canot create api key rotated email to user [%s]", payload.UserID))
}
ctxLogger.Info(fmt.Sprintf("api key rotated email sent successfully to [%s] with user ID [%s]", payload.Email, payload.UserID))
return nil
}
// UserSendPhoneDeadEmailParams are parameters for notifying a user when a phone is dead
type UserSendPhoneDeadEmailParams struct {
UserID entities.UserID
PhoneID uuid.UUID
Owner string
LastHeartbeatTimestamp time.Time
}
// SendPhoneDeadEmail sends an email to an entities.User when a phone is dead
func (service *UserService) SendPhoneDeadEmail(ctx context.Context, params *UserSendPhoneDeadEmailParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with ID [%s]", user, params.UserID))
}
if !user.NotificationHeartbeatEnabled {
ctxLogger.Info(fmt.Sprintf("[%s] email notifications disabled for user [%s] with owner [%s]", events.EventTypePhoneHeartbeatOffline, params.UserID, params.Owner))
return nil
}
email, err := service.emailFactory.PhoneDead(user, params.LastHeartbeatTimestamp, params.Owner)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create phone dead email for user [%s]", params.UserID))
}
if err = service.mailer.Send(ctx, email); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "canot send phone dead notification to user [%s]", params.UserID))
}
ctxLogger.Info(fmt.Sprintf("phone dead notification sent successfully to [%s] about [%s]", user.Email, params.Owner))
return nil
}
// StartSubscription starts a subscription for an entities.User
func (service *UserService) StartSubscription(ctx context.Context, params *events.UserSubscriptionCreatedPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, params.UserID))
}
user.SubscriptionID = ¶ms.SubscriptionID
user.SubscriptionName = params.SubscriptionName
user.SubscriptionRenewsAt = ¶ms.SubscriptionRenewsAt
user.SubscriptionStatus = ¶ms.SubscriptionStatus
user.SubscriptionEndsAt = nil
if err = service.repository.Update(ctx, user); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not update [%T] with with ID [%s] after update", user, params.UserID))
}
return nil
}
// InitiateSubscriptionCancel initiates the cancelling of a subscription on lemonsqueezy
func (service *UserService) InitiateSubscriptionCancel(ctx context.Context, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, userID))
}
if _, _, err = service.lemonsqueezyClient.Subscriptions.Cancel(ctx, *user.SubscriptionID); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not cancel subscription [%s] for [%T] with with ID [%s]", *user.SubscriptionID, user, user.ID))
}
ctxLogger.Info(fmt.Sprintf("cancelled subscription [%s] for user [%s]", *user.SubscriptionID, user.ID))
return nil
}
// GetSubscriptionUpdateURL fetches the LemonSqueezy page for updating a subscription.
func (service *UserService) GetSubscriptionUpdateURL(ctx context.Context, userID entities.UserID) (url string, err error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
return "", service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, userID))
}
subscription, _, err := service.lemonsqueezyClient.Subscriptions.Get(ctx, *user.SubscriptionID)
if err != nil {
return url, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get subscription [%s] for [%T] with with ID [%s]", *user.SubscriptionID, user, user.ID))
}
return subscription.Data.Attributes.Urls.CustomerPortal, nil
}
// CancelSubscription starts a subscription for an entities.User
func (service *UserService) CancelSubscription(ctx context.Context, params *events.UserSubscriptionCancelledPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, params.UserID))
}
user.SubscriptionID = ¶ms.SubscriptionID
user.SubscriptionName = params.SubscriptionName
user.SubscriptionRenewsAt = nil
user.SubscriptionStatus = ¶ms.SubscriptionStatus
user.SubscriptionEndsAt = ¶ms.SubscriptionEndsAt
if err = service.repository.Update(ctx, user); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not update [%T] with with ID [%s] after update", user, params.UserID))
}
return nil
}
// 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()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, params.UserID))
}
user.SubscriptionID = nil
user.SubscriptionName = entities.SubscriptionNameFree
user.SubscriptionRenewsAt = nil
user.SubscriptionStatus = nil
user.SubscriptionEndsAt = nil
if err = service.repository.Update(ctx, user); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not update [%T] with with ID [%s] after expired subscription update", user, params.UserID))
}
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 {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not get [%T] with with ID [%s]", user, params.UserID))
}
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 = ¶ms.SubscriptionID
user.SubscriptionName = params.SubscriptionName
user.SubscriptionEndsAt = params.SubscriptionEndsAt
user.SubscriptionRenewsAt = ¶ms.SubscriptionRenewsAt
user.SubscriptionStatus = ¶ms.SubscriptionStatus
if err = service.repository.Update(ctx, user); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not update [%T] with with ID [%s] after subscription update", user, params.UserID))
}
return nil
}
// DeleteAuthUser deletes an entities.AuthContext from firebase
func (service *UserService) DeleteAuthUser(ctx context.Context, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
if err := service.authClient.DeleteUser(ctx, userID.String()); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not delete [entities.AuthContext] from firebase with ID [%s]", userID))
}
ctxLogger.Info(fmt.Sprintf("deleted [entities.AuthContext] from firebase for user with ID [%s]", userID))
return nil
}
|