diff --git a/pkg/api/routes.go b/pkg/api/routes.go index c27c3ed..666c650 100644 --- a/pkg/api/routes.go +++ b/pkg/api/routes.go @@ -30,6 +30,8 @@ func Routes(s *gin.Engine, db *pg.DB) { subscriptionService := services.SubscriptionService{Db: db} subscriptionTypeService := services.SubscriptionTypeService{Db: db} + walletService.Ss = &subscriptionService + controllers.NewApiController(&apiService, api) controllers.NewAuthController(&usersService, auth) controllers.NewWalletsController(&walletService, wallet) diff --git a/pkg/models/subscriptions.go b/pkg/models/subscriptions.go index 016afde..03d661c 100644 --- a/pkg/models/subscriptions.go +++ b/pkg/models/subscriptions.go @@ -45,5 +45,6 @@ func (cm *Subscription) ToTrans() *Transaction { trans.TransactionTypeID = cm.TransactionTypeID trans.TransactionType = cm.TransactionType trans.DateCreated = cm.DateCreated + trans.SubscriptionID = cm.Id return trans } diff --git a/pkg/services/subscriptions.go b/pkg/services/subscriptions.go index 9a638f6..6c5f3ae 100644 --- a/pkg/services/subscriptions.go +++ b/pkg/services/subscriptions.go @@ -46,3 +46,37 @@ func (as *SubscriptionService) GetAll(am *models.Auth, walletId string, filtered } FilteredResponse(query, wm, filtered) } + +func (as *SubscriptionService) SubToTrans(subModel *models.Subscription) { + now := time.Now() + + currentYear, currentMonth, _ := now.Date() + currentLocation := now.Location() + + firstOfNextMonth := time.Date(currentYear, currentMonth+1, 1, 0, 0, 0, 0, currentLocation) + + startDate := subModel.StartDate.Local() + stopDate := firstOfNextMonth + if subModel.HasEnd && subModel.EndDate.Local().Before(firstOfNextMonth) { + stopDate = subModel.EndDate.Local() + } + + for startDate.Before(stopDate) { + trans := subModel.ToTrans() + trans.TransactionDate = startDate + if startDate.After(subModel.LastTransactionDate) { + as.Db.Model(trans).Insert() + subModel.LastTransactionDate = trans.TransactionDate + as.Db.Model(subModel).WherePK().Update() + } + if subModel.SubscriptionType.Type == "monthly" { + startDate = startDate.AddDate(0, subModel.CustomRange, 0) + } else if subModel.SubscriptionType.Type == "weekly" { + startDate = startDate.AddDate(0, 0, 7*subModel.CustomRange) + } else if subModel.SubscriptionType.Type == "daily" { + startDate = startDate.AddDate(0, 0, subModel.CustomRange) + } else { + startDate = startDate.AddDate(subModel.CustomRange, 0, 0) + } + } +} diff --git a/pkg/services/wallets.go b/pkg/services/wallets.go index ae68c12..7f7e219 100644 --- a/pkg/services/wallets.go +++ b/pkg/services/wallets.go @@ -11,6 +11,7 @@ import ( type WalletService struct { Db *pg.DB + Ss *SubscriptionService } func (as *WalletService) New(am *models.NewWalletBody) *models.Wallet { @@ -89,6 +90,7 @@ func (as *WalletService) GetHeader(am *models.Auth, embed string, walletId strin } for _, sub := range *subscriptions { + as.Ss.SubToTrans(&sub) startDate := sub.StartDate.Local() stopDate := firstOfMonthAfterNext if sub.HasEnd {