partial repository layer added

This commit is contained in:
Fran Jurmanović
2022-09-27 00:33:44 +02:00
parent 13ce0735d0
commit 82e97fc97f
73 changed files with 2686 additions and 1216 deletions

53
pkg/repository/api.go Normal file
View File

@@ -0,0 +1,53 @@
package repository
import (
"context"
"wallet-api/pkg/migrate"
"wallet-api/pkg/model"
"github.com/go-pg/pg/v10"
)
type ApiRepository struct {
db *pg.DB
}
func NewApiRepository(db *pg.DB) *ApiRepository {
return &ApiRepository{
db: db,
}
}
/*
GetFirst
Gets first row from API table.
Args:
context.Context: Application context
Returns:
model.ApiModel: Api object from database.
*/
func (as ApiRepository) GetFirst(ctx context.Context) model.ApiModel {
db := as.db.WithContext(ctx)
apiModel := model.ApiModel{Api: "Works"}
db.Model(&apiModel).First()
return apiModel
}
/*
PostMigrate
Starts database migration.
Args:
context.Context: Application context
string: Migration version
Returns:
*model.MessageResponse: Message response object.
*model.Exception: Exception response object.
*/
func (as ApiRepository) PostMigrate(ctx context.Context, version string) []error {
db := as.db.WithContext(ctx)
return migrate.Start(db, version)
}

View File

@@ -0,0 +1,59 @@
package repository
import (
"go.uber.org/dig"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
/*
InitializeRepositories
Initializes Dependency Injection modules for repositories
Args:
*dig.Container: Dig Container
*/
func InitializeRepositories(c *dig.Container) {
c.Provide(NewApiRepository)
c.Provide(NewSubscriptionRepository)
c.Provide(NewSubscriptionTypeRepository)
c.Provide(NewTransactionRepository)
c.Provide(NewTransactionStatusRepository)
c.Provide(NewTransactionTypeRepository)
c.Provide(NewUserRepository)
c.Provide(NewWalletRepository)
}
/*
FilteredResponse
Adds filters to query and executes it.
Args:
*pg.Query: postgres query
interface{}: model to be mapped from query execution.
*model.FilteredResponse: filter options.
*/
func FilteredResponse(qry *pg.Query, mdl interface{}, filtered *model.FilteredResponse) error {
if filtered.Page == 0 {
filtered.Page = 1
}
if filtered.Rpp == 0 {
filtered.Rpp = 20
}
if filtered.SortBy == "" {
filtered.SortBy = "date_created DESC"
}
qry = qry.Limit(filtered.Rpp).Offset((filtered.Page - 1) * filtered.Rpp).Order(filtered.SortBy)
common.GenerateEmbed(qry, filtered.Embed)
count, err := qry.SelectAndCount()
common.CheckError(err)
filtered.TotalRecords = count
filtered.Items = mdl
return err
}

View File

@@ -0,0 +1,280 @@
package repository
import (
"context"
"fmt"
"github.com/go-pg/pg/v10/orm"
"time"
"wallet-api/pkg/filter"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
type SubscriptionRepository struct {
db *pg.DB
}
func NewSubscriptionRepository(db *pg.DB) *SubscriptionRepository {
return &SubscriptionRepository{
db: db,
}
}
/*
New
Inserts new row to subscription table.
Args:
context.Context: Application context
*model.NewSubscriptionBody: Request body
Returns:
*model.Subscription: Created Subscription row object from database.
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) New(ctx context.Context, tm *model.Subscription) (*model.Subscription, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(tm).Insert()
if err != nil {
return nil, err
}
tx.Commit()
return tm, nil
}
/*
Get
Gets row from subscription table by id.
Args:
context.Context: Application context
*model.Auth: Authentication model
string: subscription id to search
params: *model.Params
Returns:
*model.Subscription: Subscription row object from database.
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) Get(ctx context.Context, am *model.Subscription, flt filter.SubscriptionFilter) (*model.Subscription, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
qry := tx.Model(am)
as.OnBeforeGetSubscriptionFilter(qry, &flt)
err := common.GenerateEmbed(qry, flt.Embed).WherePK().Select()
if err != nil {
return nil, err
}
tx.Commit()
return am, nil
}
/*
GetAll
Gets filtered rows from subscription table.
Args:
context.Context: Application context
*model.Auth: Authentication object
string: Wallet id to search
*model.FilteredResponse: filter options
Returns:
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) GetAll(ctx context.Context, am *[]model.Subscription, filtered *model.FilteredResponse, flt *filter.SubscriptionFilter) error {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
query := tx.Model(am)
as.OnBeforeGetSubscriptionFilter(query, flt)
err := FilteredResponse(query, am, filtered)
if err != nil {
return err
}
tx.Commit()
return nil
}
/*
GetAllTx
Gets filtered rows from subscription table.
Args:
context.Context: Application context
*model.Auth: Authentication object
string: Wallet id to search
*model.FilteredResponse: filter options
Returns:
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) GetAllTx(tx *pg.Tx, am *[]model.Subscription, flt *filter.SubscriptionFilter) error {
query := tx.Model(am)
as.OnBeforeGetSubscriptionFilter(query, flt)
err := query.Select()
if err != nil {
return err
}
tx.Commit()
return nil
}
/*
Edit
Updates row from subscription table by id.
Args:
context.Context: Application context
*model.SubscriptionEdit: Values to edit
string: id to search
Returns:
*model.Subscription: Edited Subscription row object from database.
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) Edit(ctx context.Context, tm *model.Subscription) (*model.Subscription, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(tm).WherePK().UpdateNotZero()
if err != nil {
return nil, err
}
tx.Commit()
return tm, nil
}
/*
End
Updates row in subscription table by id.
Ends subscription with current date.
Args:
context.Context: Application context
string: id to search
Returns:
*model.Subscription: Created Subscription row object from database.
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) End(ctx context.Context, tm *model.Subscription) (*model.Subscription, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(tm).WherePK().UpdateNotZero()
if err != nil {
return nil, err
}
tx.Commit()
return tm, nil
}
/*
SubToTrans
Generates and Inserts new Transaction rows from the subscription model.
Args:
*model.Subscription: Subscription model to generate new transactions from
*pg.Tx: Postgres query context
Returns:
*model.Exception: Exception payload.
*/
func (as *SubscriptionRepository) SubToTrans(subModel *model.Subscription, tx *pg.Tx) *model.Exception {
exceptionReturn := new(model.Exception)
now := time.Now()
currentYear, currentMonth, _ := now.Date()
currentLocation := now.Location()
transactionStatus := new(model.TransactionStatus)
firstOfNextMonth := time.Date(currentYear, currentMonth+1, 1, 0, 0, 0, 0, currentLocation)
tx.Model(transactionStatus).Where("? = ?", pg.Ident("status"), "pending").Select()
//tzFirstOfNextMonth := firstOfNextMonth.In(subModel.StartDate.Location())
startDate := subModel.StartDate
stopDate := firstOfNextMonth
if subModel.HasEnd && subModel.EndDate.Before(firstOfNextMonth) {
stopDate = subModel.EndDate
}
transactions := new([]model.Transaction)
if subModel.SubscriptionType == nil {
st := new(model.SubscriptionType)
tx.Model(st).Where("? = ?", pg.Ident("id"), subModel.SubscriptionTypeID).Select()
subModel.SubscriptionType = st
}
for startDate.Before(stopDate) {
trans := subModel.ToTrans()
trans.TransactionDate = startDate
trans.TransactionStatusID = transactionStatus.Id
if startDate.After(subModel.LastTransactionDate) && (startDate.Before(now) || startDate.Equal(now)) {
*transactions = append(*transactions, *trans)
}
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)
}
}
var err error
if len(*transactions) > 0 {
for _, trans := range *transactions {
_, err = tx.Model(&trans).Where("? = ?", pg.Ident("transaction_date"), trans.TransactionDate).Where("? = ?", pg.Ident("subscription_id"), trans.SubscriptionID).OnConflict("DO NOTHING").SelectOrInsert()
if err != nil {
_, err = tx.Model(subModel).Set("? = ?", pg.Ident("last_transaction_date"), trans.TransactionDate).WherePK().Update()
}
}
}
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400113"
exceptionReturn.Message = fmt.Sprintf("Error updating row in \"subscription\" table: %s", err)
return exceptionReturn
}
return nil
}
func (as *SubscriptionRepository) OnBeforeGetSubscriptionFilter(qry *orm.Query, flt *filter.SubscriptionFilter) {
if flt.Id != "" {
qry.Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), flt.Id)
}
if flt.WalletId != "" {
qry.Where("? = ?", pg.Ident("wallet_id"), flt.WalletId)
}
}

View File

@@ -0,0 +1,67 @@
package repository
import (
"context"
"wallet-api/pkg/filter"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
type SubscriptionTypeRepository struct {
db *pg.DB
}
func NewSubscriptionTypeRepository(db *pg.DB) *SubscriptionTypeRepository {
return &SubscriptionTypeRepository{
db: db,
}
}
/*
New
Inserts new row to subscription type table.
Args:
context.Context: Application context
*model.NewSubscriptionTypeBody: Values to create new row
Returns:
*model.SubscriptionType: Created row from database.
*model.Exception: Exception payload.
*/
func (as *SubscriptionTypeRepository) New(ctx context.Context, tm *model.SubscriptionType) (*model.SubscriptionType, error) {
db := as.db.WithContext(ctx)
_, err := db.Model(tm).Insert()
if err != nil {
return nil, err
}
return tm, nil
}
/*
GetAll
Gets all rows from subscription type table.
Args:
context.Context: Application context
string: Relations to embed
Returns:
*[]model.SubscriptionType: List of subscription type objects.
*model.Exception: Exception payload.
*/
func (as *SubscriptionTypeRepository) GetAll(ctx context.Context, flt *filter.SubscriptionTypeFilter, wm *[]model.SubscriptionType) (*[]model.SubscriptionType, error) {
db := as.db.WithContext(ctx)
query := db.Model(wm)
err := common.GenerateEmbed(query, flt.Embed).Select()
if err != nil {
return nil, err
}
return wm, nil
}

View File

@@ -0,0 +1,268 @@
package repository
import (
"context"
"fmt"
"github.com/go-pg/pg/v10/orm"
"wallet-api/pkg/filter"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
type TransactionRepository struct {
db *pg.DB
subscriptionRepository *SubscriptionRepository
transactionStatusRepository *TransactionStatusRepository
}
func NewTransactionRepository(db *pg.DB, ss *SubscriptionRepository, tsr *TransactionStatusRepository) *TransactionRepository {
return &TransactionRepository{
db: db,
subscriptionRepository: ss,
transactionStatusRepository: tsr,
}
}
/*
New row into transaction table
Inserts
Args:
context.Context: Application context
*model.NewTransactionBody: Transaction body object
Returns:
*model.Transaction: Transaction object
*model.Exception: Exception payload.
*/
func (as *TransactionRepository) New(ctx context.Context, tm *model.Transaction) (*model.Transaction, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(tm).Insert()
if err != nil {
return nil, err
}
tx.Commit()
return tm, nil
}
/*
GetAll
Gets all rows from subscription type table.
Args:
context.Context: Application context
string: Relations to embed
Returns:
*model.Exception: Exception payload.
*/
// Gets filtered rows from transaction table.
func (as *TransactionRepository) GetAll(ctx context.Context, filtered *model.FilteredResponse, flt *filter.TransactionFilter) *model.Exception {
db := as.db.WithContext(ctx)
exceptionReturn := new(model.Exception)
wm := new([]model.Transaction)
transactionStatus := new(model.TransactionStatus)
tx, _ := db.Begin()
defer tx.Rollback()
tsFlt := filter.NewTransactionStatusFilter(model.Params{})
tsFlt.Status = "completed"
_, err := as.transactionStatusRepository.GetTx(tx, transactionStatus, tsFlt)
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400117"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"transactionStatus\" table: %s", err)
return exceptionReturn
}
flt.TransactionStatusId = transactionStatus.Id
query := tx.Model(wm)
as.OnBeforeGetTransactionFilter(query, flt)
err = FilteredResponse(query, wm, filtered)
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400118"
exceptionReturn.Message = fmt.Sprintf("Error selecting row(s) in \"transaction\" table: %s", err)
return exceptionReturn
}
tx.Commit()
return nil
}
/*
Check
Checks subscriptions and create transacitons.
Args:
context.Context: Application context
string: Relations to embed
Returns:
*model.Exception: Exception payload.
*/
// Gets filtered rows from transaction table.
func (as *TransactionRepository) Check(ctx context.Context, filtered *model.FilteredResponse, flt *filter.TransactionFilter) *model.Exception {
db := as.db.WithContext(ctx)
wm := new([]model.Transaction)
sm := new([]model.Subscription)
transactionStatus := new(model.TransactionStatus)
exceptionReturn := new(model.Exception)
tx, _ := db.Begin()
defer tx.Rollback()
tsFlt := filter.NewTransactionStatusFilter(model.Params{})
tsFlt.Status = "pending"
_, err := as.transactionStatusRepository.GetTx(tx, transactionStatus, tsFlt)
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400119"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"transactionStatus\" table: %s", err)
return exceptionReturn
}
flt.TransactionStatusId = transactionStatus.Id
smFlt := filter.NewSubscriptionFilter(model.Params{})
smFlt.Id = flt.Id
smFlt.WalletId = flt.WalletId
as.subscriptionRepository.GetAllTx(tx, sm, smFlt)
for _, sub := range *sm {
if sub.HasNew() {
as.subscriptionRepository.SubToTrans(&sub, tx)
}
}
qry := tx.Model(wm)
as.OnBeforeGetTransactionFilter(qry, flt)
err = FilteredResponse(qry, wm, filtered)
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400120"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"transaction\" table: %s", err)
return exceptionReturn
}
tx.Commit()
return nil
}
/*
Edit
Updates row in transaction table by id.
Args:
context.Context: Application context
*model.TransactionEdit: Object to edit
string: id to search
Returns:
*model.Transaction: Transaction object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionRepository) Edit(ctx context.Context, tm *model.Transaction) (*model.Transaction, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(tm).WherePK().UpdateNotZero()
if err != nil {
return nil, err
}
err = tx.Model(tm).WherePK().Select()
if err != nil {
return nil, err
}
tx.Commit()
return tm, nil
}
/*
Bulk Edit
Updates row in transaction table by id.
Args:
context.Context: Application context
?[]model.Transaction Bulk Edit: Object to edit
string: id to search
Returns:
*model.Transaction: Transaction object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionRepository) BulkEdit(ctx context.Context, transactions *[]model.Transaction) (*[]model.Transaction, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(transactions).WherePK().UpdateNotZero()
if err != nil {
return nil, err
}
tx.Commit()
return transactions, nil
}
/*
Get
Gets row from transaction table by id.
Args:
context.Context: Application context
*model.Auth: Authentication object
string: id to search
*model.Params: url query parameters
Returns:
*model.Transaction: Transaction object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionRepository) Get(ctx context.Context, flt *filter.TransactionFilter) (*model.Transaction, error) {
db := as.db.WithContext(ctx)
wm := new(model.Transaction)
tx, _ := db.Begin()
defer tx.Rollback()
qry := tx.Model(wm)
as.OnBeforeGetTransactionFilter(qry, flt)
err := common.GenerateEmbed(qry, flt.Embed).WherePK().Select()
if err != nil {
return nil, err
}
tx.Commit()
return wm, nil
}
func (as *TransactionRepository) OnBeforeGetTransactionFilter(qry *orm.Query, flt *filter.TransactionFilter) {
if flt.WalletId != "" {
qry.Where("? = ?", pg.Ident("wallet_id"), flt.WalletId)
}
if flt.Id != "" {
qry.Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), flt.Id)
}
if flt.NoPending && flt.TransactionStatusId != "" {
qry.Where("? = ?", pg.Ident("transaction_status_id"), flt.TransactionStatusId)
}
}

View File

@@ -0,0 +1,146 @@
package repository
import (
"context"
"fmt"
"github.com/go-pg/pg/v10/orm"
"wallet-api/pkg/filter"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
type TransactionStatusRepository struct {
db *pg.DB
}
func NewTransactionStatusRepository(db *pg.DB) *TransactionStatusRepository {
return &TransactionStatusRepository{
db: db,
}
}
/*
New
Inserts new row to transaction status table.
Args:
context.Context: Application context
*model.NewTransactionStatusBody: object to create
Returns:
*model.TransactionType: Transaction Type object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionStatusRepository) New(ctx context.Context, body *model.NewTransactionStatusBody) (*model.TransactionStatus, *model.Exception) {
db := as.db.WithContext(ctx)
tm := new(model.TransactionStatus)
exceptionReturn := new(model.Exception)
tm.Init()
tm.Name = body.Name
tm.Status = body.Status
_, err := db.Model(tm).Insert()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400123"
exceptionReturn.Message = fmt.Sprintf("Error inserting row in \"transactionStatus\" table: %s", err)
return nil, exceptionReturn
}
return tm, nil
}
/*
GetAll
Gets all rows from transaction status table.
Args:
context.Context: Application context
string: Relations to embed
Returns:
*[]model.TransactionStatus: List of Transaction status objects from database.
*model.Exception: Exception payload.
*/
func (as *TransactionStatusRepository) GetAll(ctx context.Context, embed string) (*[]model.TransactionStatus, *model.Exception) {
db := as.db.WithContext(ctx)
wm := new([]model.TransactionStatus)
exceptionReturn := new(model.Exception)
query := db.Model(wm)
err := common.GenerateEmbed(query, embed).Select()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400124"
exceptionReturn.Message = fmt.Sprintf("Error selecting rows in \"transactionStatus\" table: %s", err)
return nil, exceptionReturn
}
return wm, nil
}
/*
Get
Gets row from transactionStatus table by id.
Args:
context.Context: Application context
*model.Auth: Authentication model
string: transactionStatus id to search
params: *model.Params
Returns:
*model.Subscription: Subscription row object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionStatusRepository) Get(ctx context.Context, am *model.TransactionStatus, flt filter.TransactionStatusFilter) (*model.TransactionStatus, error) {
db := as.db.WithContext(ctx)
tx, _ := db.Begin()
defer tx.Rollback()
qry := tx.Model(am)
err := common.GenerateEmbed(qry, flt.Embed).WherePK().Select()
if err != nil {
return nil, err
}
tx.Commit()
return am, nil
}
/*
GetTx
Gets row from transactionStatus table by id.
Args:
context.Context: Application context
*model.Auth: Authentication model
string: transactionStatus id to search
params: *model.Params
Returns:
*model.Subscription: Subscription row object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionStatusRepository) GetTx(tx *pg.Tx, am *model.TransactionStatus, flt *filter.TransactionStatusFilter) (*model.TransactionStatus, error) {
qry := tx.Model(am)
as.OnBeforeGetTransactionStatusFilter(qry, flt)
err := common.GenerateEmbed(qry, flt.Embed).WherePK().Select()
if err != nil {
return nil, err
}
return am, nil
}
func (as *TransactionStatusRepository) OnBeforeGetTransactionStatusFilter(qry *orm.Query, flt *filter.TransactionStatusFilter) {
if flt.Status != "" {
qry.Where("? = ?", pg.Ident("status"), flt.Status)
}
}

View File

@@ -0,0 +1,83 @@
package repository
import (
"context"
"fmt"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
type TransactionTypeRepository struct {
db *pg.DB
}
func NewTransactionTypeRepository(db *pg.DB) *TransactionTypeRepository {
return &TransactionTypeRepository{
db: db,
}
}
/*
New
Inserts new row to transaction type table.
Args:
context.Context: Application context
*model.NewTransactionTypeBody: object to create
Returns:
*model.TransactionType: Transaction Type object from database.
*model.Exception: Exception payload.
*/
func (as *TransactionTypeRepository) New(ctx context.Context, body *model.NewTransactionTypeBody) (*model.TransactionType, *model.Exception) {
db := as.db.WithContext(ctx)
tm := new(model.TransactionType)
exceptionReturn := new(model.Exception)
tm.Init()
tm.Name = body.Name
tm.Type = body.Type
_, err := db.Model(tm).Insert()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400125"
exceptionReturn.Message = fmt.Sprintf("Error inserting row in \"transactionTypes\" table: %s", err)
return nil, exceptionReturn
}
return tm, nil
}
/*
GetAll
Gets all rows from transaction type table.
Args:
context.Context: Application context
string: Relations to embed
Returns:
*[]model.TransactionType: List of Transaction type objects from database.
*model.Exception: Exception payload.
*/
func (as *TransactionTypeRepository) GetAll(ctx context.Context, embed string) (*[]model.TransactionType, *model.Exception) {
db := as.db.WithContext(ctx)
wm := new([]model.TransactionType)
exceptionReturn := new(model.Exception)
query := db.Model(wm)
err := common.GenerateEmbed(query, embed).Select()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400133"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"transactionTypes\" table: %s", err)
return nil, exceptionReturn
}
return wm, nil
}

210
pkg/repository/user.go Normal file
View File

@@ -0,0 +1,210 @@
package repository
import (
"context"
"os"
"time"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"wallet-api/pkg/utl/configs"
jwt "github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
"github.com/go-pg/pg/v10"
)
type UserRepository struct {
db *pg.DB
}
func NewUserRepository(db *pg.DB) *UserRepository {
return &UserRepository{
db: db,
}
}
/*
Create
Inserts new row to users table.
Args:
context.Context: Application context
*model.User: User object to create
Returns:
*model.User: User object from database
*model.Exception
*/
func (us *UserRepository) Create(ctx context.Context, registerBody *model.User) (*model.User, *model.Exception) {
db := us.db.WithContext(ctx)
check := new(model.User)
exceptionReturn := new(model.Exception)
tx, _ := db.Begin()
defer tx.Rollback()
tx.Model(check).Where("? = ?", pg.Ident("username"), registerBody.Username).WhereOr("? = ?", pg.Ident("email"), registerBody.Email).Select()
if check.Username != "" || check.Email != "" {
exceptionReturn.Message = "User already exists"
exceptionReturn.ErrorCode = "400101"
exceptionReturn.StatusCode = 400
return check, exceptionReturn
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(registerBody.Password), bcrypt.DefaultCost)
common.CheckError(err)
registerBody.Password = string(hashedPassword)
_, err = tx.Model(registerBody).Insert()
if err != nil {
exceptionReturn.Message = "Error creating user"
exceptionReturn.ErrorCode = "400102"
exceptionReturn.StatusCode = 400
}
tx.Commit()
return registerBody, exceptionReturn
}
/*
Login
Gets row from users table by email and valid password.
Args:
context.Context: Application context
*model.Login: object to search
Returns:
*model.Token: new session token
*model.Exception
*/
func (us *UserRepository) Login(ctx context.Context, loginBody *model.Login) (*model.Token, *model.Exception) {
db := us.db.WithContext(ctx)
check := new(model.User)
exceptionReturn := new(model.Exception)
tokenPayload := new(model.Token)
tx, _ := db.Begin()
defer tx.Rollback()
tx.Model(check).Where("? = ?", pg.Ident("email"), loginBody.Email).Select()
if check.Email == "" {
exceptionReturn.Message = "Email not found"
exceptionReturn.ErrorCode = "400103"
exceptionReturn.StatusCode = 400
return tokenPayload, exceptionReturn
}
if !check.IsActive {
exceptionReturn.Message = "Can't log in. User is deactivated."
exceptionReturn.ErrorCode = "400106"
exceptionReturn.StatusCode = 400
return tokenPayload, exceptionReturn
}
if bcrypt.CompareHashAndPassword([]byte(check.Password), []byte(loginBody.Password)) != nil {
exceptionReturn.Message = "Incorrect password"
exceptionReturn.ErrorCode = "400104"
exceptionReturn.StatusCode = 400
return tokenPayload, exceptionReturn
}
token, err := CreateToken(check, loginBody.RememberMe)
common.CheckError(err)
tokenPayload.Token = token
tx.Commit()
return tokenPayload, exceptionReturn
}
/*
Deactivate
Updates row in users table.
IsActive column is set to false
Args:
context.Context: Application context
*model.Auth: Authentication object
Returns:
*model.MessageResponse
*model.Exception
*/
func (us *UserRepository) Deactivate(ctx context.Context, auth *model.Auth) (*model.MessageResponse, *model.Exception) {
db := us.db.WithContext(ctx)
mm := new(model.MessageResponse)
me := new(model.Exception)
um := new(model.User)
tx, _ := db.Begin()
defer tx.Rollback()
err := tx.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Select()
if err != nil {
me.ErrorCode = "404101"
me.Message = "User not found"
me.StatusCode = 404
return mm, me
}
um.IsActive = false
_, err = tx.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Update()
if err != nil {
me.ErrorCode = "400105"
me.Message = "Could not deactivate user"
me.StatusCode = 400
return mm, me
}
mm.Message = "User successfully deactivated."
tx.Commit()
return mm, me
}
/*
CreateToken
Generates new jwt token.
It encodes the user id. Based on rememberMe it is valid through 48hours or 2hours.
Args:
*model.User: User object to encode
bool: Should function generate longer lasting token (48hrs)
Returns:
string: Generated token
error: Error that occured in the process
*/
func CreateToken(user *model.User, rememberMe bool) (string, error) {
atClaims := jwt.MapClaims{}
atClaims["authorized"] = true
atClaims["id"] = user.Id
if rememberMe {
atClaims["exp"] = time.Now().Add(time.Hour * 48).Unix()
} else {
atClaims["exp"] = time.Now().Add(time.Hour * 2).Unix()
}
secret := os.Getenv("ACCESS_SECRET")
if secret == "" {
secret = configs.Secret
}
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
token, err := at.SignedString([]byte(secret))
return token, err
}

323
pkg/repository/wallet.go Normal file
View File

@@ -0,0 +1,323 @@
package repository
import (
"context"
"fmt"
"time"
"wallet-api/pkg/model"
"wallet-api/pkg/utl/common"
"github.com/go-pg/pg/v10"
)
type WalletRepository struct {
db *pg.DB
subscriptionRepository *SubscriptionRepository
}
func NewWalletRepository(db *pg.DB, ss *SubscriptionRepository) *WalletRepository {
return &WalletRepository{
db: db,
subscriptionRepository: ss,
}
}
/*
New
Inserts row to wallets table.
Args:
context.Context: Application context
*model.NewWalletBody: Object to be inserted
Returns:
*model.Wallet: Wallet object from database.
*model.Exception: Exception payload.
*/
func (as *WalletRepository) New(ctx context.Context, am *model.NewWalletBody) (*model.Wallet, *model.Exception) {
db := as.db.WithContext(ctx)
exceptionReturn := new(model.Exception)
walletModel := new(model.Wallet)
walletModel.Init()
walletModel.UserID = am.UserID
walletModel.Name = am.Name
_, err := db.Model(walletModel).Insert()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400126"
exceptionReturn.Message = fmt.Sprintf("Error inserting row in \"wallets\" table: %s", err)
return nil, exceptionReturn
}
return walletModel, nil
}
/*
Edit
Updates row in wallets table by id.
Args:
context.Context: Application context
*model.WalletEdit: Object to be edited
string: id to search
Returns:
*model.Wallet: Wallet object from database.
*model.Exception: Exception payload.
*/
func (as *WalletRepository) Edit(ctx context.Context, body *model.WalletEdit, id string) (*model.Wallet, *model.Exception) {
db := as.db.WithContext(ctx)
exceptionReturn := new(model.Exception)
tm := new(model.Wallet)
tm.Id = id
tm.Name = body.Name
tx, _ := db.Begin()
defer tx.Rollback()
_, err := tx.Model(tm).WherePK().UpdateNotZero()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400127"
exceptionReturn.Message = fmt.Sprintf("Error updating row in \"wallets\" table: %s", err)
return nil, exceptionReturn
}
tx.Commit()
return tm, nil
}
/*
Get
Gets row in wallets table by id.
Args:
context.Context: Application context
string: id to search
*model.Params: url query parameters
Returns:
*model.Wallet: Wallet object from database
*model.Exception: Exception payload.
*/
func (as *WalletRepository) Get(ctx context.Context, id string, params *model.Params) (*model.Wallet, *model.Exception) {
db := as.db.WithContext(ctx)
exceptionReturn := new(model.Exception)
wm := new(model.Wallet)
wm.Id = id
tx, _ := db.Begin()
defer tx.Rollback()
qry := tx.Model(wm)
err := common.GenerateEmbed(qry, params.Embed).WherePK().Select()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400128"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"wallets\" table: %s", err)
return nil, exceptionReturn
}
tx.Commit()
return wm, nil
}
/*
GetAll
Gets filtered rows from wallets table.
Args:
context.Context: Application context
*model.Auth: Authentication object
*model.FilteredResponse: filter options
Returns:
*model.Exception: Exception payload.
*/
func (as *WalletRepository) GetAll(ctx context.Context, am *model.Auth, filtered *model.FilteredResponse) *model.Exception {
exceptionReturn := new(model.Exception)
db := as.db.WithContext(ctx)
wm := new([]model.Wallet)
query := db.Model(wm).Where("? = ?", pg.Ident("user_id"), am.Id)
err := FilteredResponse(query, wm, filtered)
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400134"
exceptionReturn.Message = fmt.Sprintf("Error selecting rows in \"wallets\" table: %s", err)
return exceptionReturn
}
return nil
}
/*
GetHeader
Gets row from wallets table.
Calculates previous month, current and next month totals.
Args:
context.Context: Application context
*model.Auth: Authentication object
string: wallet id to search
Returns:
*model.WalletHeader: generated wallet header object
*model.Exception: Exception payload.
*/
func (as *WalletRepository) GetHeader(ctx context.Context, am *model.Auth, walletId string) (*model.WalletHeader, *model.Exception) {
db := as.db.WithContext(ctx)
wm := new(model.WalletHeader)
wallets := new([]model.WalletTransactions)
transactions := new([]model.Transaction)
subscriptions := new([]model.Subscription)
transactionStatus := new(model.TransactionStatus)
exceptionReturn := new(model.Exception)
tx, _ := db.Begin()
defer tx.Rollback()
err := tx.Model(transactionStatus).Where("? = ?", pg.Ident("status"), "completed").Select()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400130"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"transactionStatuses\" table: %s", err)
return nil, exceptionReturn
}
query2 := tx.Model(subscriptions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType").Relation("SubscriptionType")
if walletId != "" {
query2.Where("? = ?", pg.Ident("wallet_id"), walletId)
}
query2.Select()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400131"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"subscriptions\" table: %s", err)
return nil, exceptionReturn
}
now := time.Now()
currentYear, currentMonth, _ := now.Date()
currentLocation := now.Location()
firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation)
firstOfNextMonth := time.Date(currentYear, currentMonth+1, 1, 0, 0, 0, 0, currentLocation)
firstOfMonthAfterNext := time.Date(currentYear, currentMonth+2, 1, 0, 0, 0, 0, currentLocation)
query := tx.Model(transactions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType")
if walletId != "" {
query.Where("? = ?", pg.Ident("wallet_id"), walletId)
}
query = query.Where("? = ?", pg.Ident("transaction_status_id"), transactionStatus.Id)
query.Select()
if err != nil {
exceptionReturn.StatusCode = 400
exceptionReturn.ErrorCode = "400132"
exceptionReturn.Message = fmt.Sprintf("Error selecting row in \"transactions\" table: %s", err)
return nil, exceptionReturn
}
tx.Commit()
for _, sub := range *subscriptions {
stopDate := firstOfMonthAfterNext
if sub.HasEnd && sub.EndDate.Before(firstOfMonthAfterNext) {
stopDate = sub.EndDate
}
startDate := sub.StartDate
for startDate.Before(stopDate) {
trans := sub.ToTrans()
trans.TransactionDate = startDate
if startDate.After(firstOfNextMonth) || startDate.Equal(firstOfNextMonth) {
*transactions = append(*transactions, *trans)
}
if sub.SubscriptionType.Type == "monthly" {
startDate = startDate.AddDate(0, sub.CustomRange, 0)
} else if sub.SubscriptionType.Type == "weekly" {
startDate = startDate.AddDate(0, 0, 7*sub.CustomRange)
} else if sub.SubscriptionType.Type == "daily" {
startDate = startDate.AddDate(0, 0, sub.CustomRange)
} else {
startDate = startDate.AddDate(sub.CustomRange, 0, 0)
}
}
}
for _, trans := range *transactions {
addWhere(wallets, trans.WalletID, trans)
}
for i, wallet := range *wallets {
for _, trans := range wallet.Transactions {
// tzFirstOfMonthAfterNext := firstOfMonthAfterNext.In(trans.TransactionDate.Location())
// tzFirstOfNextMonth := firstOfNextMonth.In(trans.TransactionDate.Location())
// tzFirstOfMonth := firstOfMonth.In(trans.TransactionDate.Location())
if trans.TransactionDate.Before(firstOfNextMonth) && trans.TransactionDate.After(firstOfMonth) || trans.TransactionDate.Equal(firstOfMonth) {
if trans.TransactionType.Type == "expense" {
(*wallets)[i].CurrentBalance -= trans.Amount
} else {
(*wallets)[i].CurrentBalance += trans.Amount
}
} else if trans.TransactionDate.Before(firstOfMonthAfterNext) && trans.TransactionDate.After(firstOfNextMonth) {
if trans.TransactionType.Type == "expense" {
(*wallets)[i].NextMonth -= trans.Amount
} else {
(*wallets)[i].NextMonth += trans.Amount
}
} else if trans.TransactionDate.Before(firstOfMonth) {
if trans.TransactionType.Type == "expense" {
(*wallets)[i].LastMonth -= trans.Amount
} else {
(*wallets)[i].LastMonth += trans.Amount
}
}
}
}
for _, wallet := range *wallets {
wm.LastMonth += wallet.LastMonth
wm.CurrentBalance += wallet.CurrentBalance + wallet.LastMonth
wm.NextMonth += wallet.NextMonth + wallet.CurrentBalance + wallet.LastMonth
}
wm.Currency = "USD"
wm.WalletId = walletId
return wm, nil
}
/*
addWhere
Appends Transaction to the belonging walletId.
If missing, it creates the item list.
Args:
*[]model.WalletTransactions: list to append to
string: wallet id to check
model.Transaction: Transaction to append
Returns:
*model.Exception: Exception payload.
*/
func addWhere(s *[]model.WalletTransactions, walletId string, e model.Transaction) {
var exists bool
for a := range *s {
if (*s)[a].WalletId == walletId {
(*s)[a].Transactions = append((*s)[a].Transactions, e)
exists = true
}
}
if !exists {
var walletTransaction model.WalletTransactions
walletTransaction.WalletId = walletId
walletTransaction.Transactions = append(walletTransaction.Transactions, e)
*s = append(*s, walletTransaction)
}
}