new licenceController, moved api handling & renaming things

This commit is contained in:
Alex
2024-10-10 20:54:20 +02:00
parent fca5af2c9a
commit d54f2ae2e6
18 changed files with 259 additions and 220 deletions

View File

@@ -99,13 +99,13 @@ func TestSuite(t *testing.T) {
var subscriptionRepo repositories.SubscriptionModelsRepositoryInterface = &repositories.SubscriptionModelsRepository{}
membershipService := &services.MembershipService{Repo: membershipRepo, SubscriptionRepo: subscriptionRepo}
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
var licenceRepo repositories.LicenceInterface = &repositories.LicenceRepository{}
var userRepo repositories.UserRepositoryInterface = &repositories.UserRepository{}
userService := &services.UserService{Repo: userRepo, Licences: licenceRepo}
driversLicenceService := &services.DriversLicenceService{Repo: licenceRepo}
licenceService := &services.LicenceService{Repo: licenceRepo}
Uc = &UserController{Service: userService, DriversLicenceService: driversLicenceService, EmailService: emailService, ConsentService: consentService, BankAccountService: bankAccountService, MembershipService: membershipService}
Uc = &UserController{Service: userService, LicenceService: licenceService, EmailService: emailService, ConsentService: consentService, BankAccountService: bankAccountService, MembershipService: membershipService}
Mc = &MembershipController{Service: *membershipService}
Cc = &ContactController{EmailService: emailService}
@@ -147,23 +147,23 @@ func TestSuite(t *testing.T) {
}
func initLicenceCategories() error {
categories := []models.LicenceCategory{
{Category: "AM"},
{Category: "A1"},
{Category: "A2"},
{Category: "A"},
{Category: "B"},
{Category: "C1"},
{Category: "C"},
{Category: "D1"},
{Category: "D"},
{Category: "BE"},
{Category: "C1E"},
{Category: "CE"},
{Category: "D1E"},
{Category: "DE"},
{Category: "T"},
{Category: "L"},
categories := []models.Category{
{Name: "AM"},
{Name: "A1"},
{Name: "A2"},
{Name: "A"},
{Name: "B"},
{Name: "C1"},
{Name: "C"},
{Name: "D1"},
{Name: "D"},
{Name: "BE"},
{Name: "C1E"},
{Name: "CE"},
{Name: "D1E"},
{Name: "DE"},
{Name: "T"},
{Name: "L"},
}
for _, category := range categories {
result := database.DB.Create(&category)
@@ -258,7 +258,7 @@ func getBaseUser() models.User {
Phone: "01738484993",
BankAccount: models.BankAccount{IBAN: "DE89370400440532013000"},
Membership: models.Membership{SubscriptionModel: models.SubscriptionModel{Name: "Basic"}},
DriversLicence: models.DriversLicence{},
Licence: models.Licence{},
ProfilePicture: "",
Password: "password123",
Company: "",

View File

@@ -0,0 +1,31 @@
package controllers
import (
"GoMembership/internal/services"
"GoMembership/pkg/logger"
"net/http"
"github.com/gin-gonic/gin"
)
type LicenceController struct {
Service services.LicenceService
}
func (lc *LicenceController) GetAllCategories(c *gin.Context) {
categories, err := lc.Service.GetAllCategories()
if err != nil {
logger.Error.Printf("Error retrieving licence categories: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"errors": []gin.H{{
"field": "general",
"key": "validation.internal_server_error",
}}})
return
}
logger.Error.Printf("categories: %v", categories)
c.JSON(http.StatusOK, gin.H{
"licence_categories": categories,
})
}

View File

@@ -46,3 +46,19 @@ func (mc *MembershipController) RegisterSubscription(c *gin.Context) {
"id": id,
})
}
func (mc *MembershipController) GetSubscriptions(c *gin.Context) {
subscriptions, err := mc.Service.GetSubscriptions(nil)
if err != nil {
logger.Error.Printf("Error retrieving subscriptions: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"errors": []gin.H{{
"field": "general",
"key": "validation.internal_server_error",
}}})
return
}
c.JSON(http.StatusOK, gin.H{
"subscriptions": subscriptions,
})
}

View File

@@ -19,12 +19,12 @@ import (
)
type UserController struct {
Service services.UserServiceInterface
EmailService *services.EmailService
ConsentService services.ConsentServiceInterface
BankAccountService services.BankAccountServiceInterface
MembershipService services.MembershipServiceInterface
DriversLicenceService services.DriversLicenceInterface
Service services.UserServiceInterface
EmailService *services.EmailService
ConsentService services.ConsentServiceInterface
BankAccountService services.BankAccountServiceInterface
MembershipService services.MembershipServiceInterface
LicenceService services.LicenceInterface
}
type RegistrationData struct {
@@ -172,28 +172,8 @@ func (uc *UserController) CurrentUserHandler(c *gin.Context) {
return
}
subscriptions, err := uc.MembershipService.GetSubscriptions(nil)
if err != nil {
logger.Error.Printf("Error retrieving subscriptions: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"errors": []gin.H{{
"field": "general",
"key": "validation.internal_server_error",
}}})
return
}
licenceCategories, err := uc.DriversLicenceService.GetAllCategories()
if err != nil {
logger.Error.Printf("Error retrieving licence categories: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"errors": []gin.H{{
"field": "general",
"key": "validation.internal_server_error",
}}})
return
}
c.JSON(http.StatusOK, gin.H{
"user": user.Safe(),
"subscriptions": subscriptions,
"licence_categories": licenceCategories,
"user": user.Safe(),
})
}

View File

@@ -75,7 +75,7 @@ func testUserController(t *testing.T) {
loginEmail, loginCookie := testLoginHandler(t)
logoutCookie := testCurrentUserHandler(t, loginEmail, loginCookie)
testUpdateUser(t, loginEmail, loginCookie)
testUpdateUser(t, loginCookie)
testLogoutHandler(t, logoutCookie)
}
@@ -413,7 +413,7 @@ func validateUser(assert bool, wantDBData map[string]interface{}) error {
return nil
}
func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
func testUpdateUser(t *testing.T, loginCookie http.Cookie) {
invalidCookie := http.Cookie{
Name: "jwt",
@@ -480,7 +480,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
},
},
{
name: "Change LicenceNumber",
name: "Change Number",
setupCookie: func(req *http.Request) {
req.AddCookie(&loginCookie)
},
@@ -489,7 +489,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.FirstName = "John Updated"
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
u.Licence.Number = "B072RRE2I50"
},
expectedStatus: http.StatusAccepted,
},
@@ -503,11 +503,11 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.FirstName = "John Updated"
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
u.Licence.Number = "B072RRE2I50"
var licenceRepo repositories.LicenceInterface = &repositories.LicenceRepository{}
category, err := licenceRepo.FindCategoryByName("B")
assert.NoError(t, err)
u.DriversLicence.LicenceCategories = []models.LicenceCategory{category}
u.Licence.Categories = []models.Category{category}
},
expectedStatus: http.StatusAccepted,
},
@@ -521,12 +521,12 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.FirstName = "John Updated"
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
u.Licence.Number = "B072RRE2I50"
var licenceRepo repositories.LicenceInterface = &repositories.LicenceRepository{}
category, err := licenceRepo.FindCategoryByName("A")
category2, err := licenceRepo.FindCategoryByName("BE")
assert.NoError(t, err)
u.DriversLicence.LicenceCategories = []models.LicenceCategory{category, category2}
u.Licence.Categories = []models.Category{category, category2}
},
expectedStatus: http.StatusAccepted,
},
@@ -540,11 +540,11 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.FirstName = "John Updated"
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
u.Licence.Number = "B072RRE2I50"
var licenceRepo repositories.LicenceInterface = &repositories.LicenceRepository{}
category, err := licenceRepo.FindCategoryByName("A")
assert.NoError(t, err)
u.DriversLicence.LicenceCategories = []models.LicenceCategory{category}
u.Licence.Categories = []models.Category{category}
},
expectedStatus: http.StatusAccepted,
},
@@ -558,8 +558,8 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.FirstName = "John Updated"
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
u.DriversLicence.LicenceCategories = []models.LicenceCategory{}
u.Licence.Number = "B072RRE2I50"
u.Licence.Categories = []models.Category{}
},
expectedStatus: http.StatusAccepted,
},
@@ -573,7 +573,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.ID = 1
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
u.Licence.Number = "B072RRE2I50"
u.FirstName = "John Missing ID"
},
expectedStatus: http.StatusForbidden,
@@ -590,7 +590,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.Password = ""
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
u.Licence.Number = "B072RRE2I50"
u.Password = "NewPassword"
},
expectedStatus: http.StatusAccepted,
@@ -713,23 +713,23 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
assert.Equal(t, updatedUser.Membership.SubscriptionModelID, updatedUserFromDB.Membership.SubscriptionModelID, "Membership.SubscriptionModelID mismatch")
assert.Equal(t, updatedUser.Membership.ParentMembershipID, updatedUserFromDB.Membership.ParentMembershipID, "Membership.ParentMembershipID mismatch")
if updatedUser.DriversLicence.Status == 0 {
updatedUser.DriversLicence.Status = constants.UnverifiedStatus
if updatedUser.Licence.Status == 0 {
updatedUser.Licence.Status = constants.UnverifiedStatus
}
assert.Equal(t, updatedUser.DriversLicence.Status, updatedUserFromDB.DriversLicence.Status, "DriversLicence.Status mismatch")
assert.Equal(t, updatedUser.DriversLicence.LicenceNumber, updatedUserFromDB.DriversLicence.LicenceNumber, "DriversLicence.LicenceNumber mismatch")
assert.Equal(t, updatedUser.DriversLicence.IssuedDate, updatedUserFromDB.DriversLicence.IssuedDate, "DriversLicence.IssuedDate mismatch")
assert.Equal(t, updatedUser.DriversLicence.ExpirationDate, updatedUserFromDB.DriversLicence.ExpirationDate, "DriversLicence.ExpirationDate mismatch")
assert.Equal(t, updatedUser.DriversLicence.IssuingCountry, updatedUserFromDB.DriversLicence.IssuingCountry, "DriversLicence.IssuingCountry mismatch")
assert.Equal(t, updatedUser.Licence.Status, updatedUserFromDB.Licence.Status, "Licence.Status mismatch")
assert.Equal(t, updatedUser.Licence.Number, updatedUserFromDB.Licence.Number, "Licence.Number mismatch")
assert.Equal(t, updatedUser.Licence.IssuedDate, updatedUserFromDB.Licence.IssuedDate, "Licence.IssuedDate mismatch")
assert.Equal(t, updatedUser.Licence.ExpirationDate, updatedUserFromDB.Licence.ExpirationDate, "Licence.ExpirationDate mismatch")
assert.Equal(t, updatedUser.Licence.IssuingCountry, updatedUserFromDB.Licence.IssuingCountry, "Licence.IssuingCountry mismatch")
// For slices or more complex nested structures, you might want to use deep equality checks
assert.ElementsMatch(t, updatedUser.Consents, updatedUserFromDB.Consents, "Consents mismatch")
if len(updatedUser.DriversLicence.LicenceCategories) > 0 {
for i := range updatedUser.DriversLicence.LicenceCategories {
assert.Equal(t, updatedUser.DriversLicence.LicenceCategories[i].Category, updatedUserFromDB.DriversLicence.LicenceCategories[i].Category, "LicenceCategory Category mismatch at index %d", i)
if len(updatedUser.Licence.Categories) > 0 {
for i := range updatedUser.Licence.Categories {
assert.Equal(t, updatedUser.Licence.Categories[i].Name, updatedUserFromDB.Licence.Categories[i].Name, "Category Category mismatch at index %d", i)
}
} else {
assert.Emptyf(t, updatedUserFromDB.DriversLicence.LicenceCategories, "Categories aren't empty when they should")
assert.Emptyf(t, updatedUserFromDB.Licence.Categories, "Categories aren't empty when they should")
}
}
})
@@ -1094,18 +1094,18 @@ func getTestUsers() []RegisterUserTest {
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
user.Email = "john.wronglicence.doe@example.com"
user.DriversLicence.LicenceNumber = "AAAA12345AA"
user.Licence.Number = "AAAA12345AA"
return user
})),
},
{
Name: "Correct DriversLicence number, should pass",
Name: "Correct Licence number, should pass",
WantResponse: http.StatusCreated,
WantDBData: map[string]interface{}{"email": "john.correctLicenceNumber@example.com"},
Assert: true,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
user.Email = "john.correctLicenceNumber@example.com"
user.DriversLicence.LicenceNumber = "B072RRE2I55"
user.Licence.Number = "B072RRE2I55"
return user
})),
},

View File

@@ -27,8 +27,8 @@ func Open(dbPath string, adminMail string) error {
&models.Membership{},
&models.Consent{},
&models.Verification{},
&models.DriversLicence{},
&models.LicenceCategory{},
&models.Licence{},
&models.Category{},
&models.BankAccount{}); err != nil {
logger.Error.Fatalf("Couldn't create database: %v", err)
return err
@@ -82,24 +82,24 @@ func createSubscriptionModels() []models.SubscriptionModel {
}
}
func createLicenceCategories() []models.LicenceCategory {
return []models.LicenceCategory{
{Category: "AM"},
{Category: "A1"},
{Category: "A2"},
{Category: "A"},
{Category: "B"},
{Category: "C1"},
{Category: "C"},
{Category: "D1"},
{Category: "D"},
{Category: "BE"},
{Category: "C1E"},
{Category: "CE"},
{Category: "D1E"},
{Category: "DE"},
{Category: "T"},
{Category: "L"},
func createLicenceCategories() []models.Category {
return []models.Category{
{Name: "AM"},
{Name: "A1"},
{Name: "A2"},
{Name: "A"},
{Name: "B"},
{Name: "C1"},
{Name: "C"},
{Name: "D1"},
{Name: "D"},
{Name: "BE"},
{Name: "C1E"},
{Name: "CE"},
{Name: "D1E"},
{Name: "DE"},
{Name: "T"},
{Name: "L"},
}
}
@@ -143,7 +143,7 @@ func createAdmin(userMail string, subscriptionModelID uint) (*models.User, error
SubscriptionModelID: subscriptionModelID,
},
BankAccount: models.BankAccount{},
DriversLicence: models.DriversLicence{
Licence: models.Licence{
Status: constants.UnverifiedStatus,
},
}, nil

View File

@@ -4,17 +4,17 @@ import (
"time"
)
type DriversLicence struct {
ID uint `json:"id" gorm:"primaryKey"`
Status int8 `json:"status" binding:"omitempty,number"`
LicenceNumber string `json:"number" binding:"omitempty,euDriversLicence,safe_content"`
IssuedDate time.Time `json:"issued_date" binding:"omitempty,lte"`
ExpirationDate time.Time `json:"expiration_date" binding:"omitempty,gt"`
IssuingCountry string `json:"country" binding:"safe_content"`
LicenceCategories []LicenceCategory `json:"licence_categories" gorm:"many2many:licence_2_categories"`
type Licence struct {
ID uint `json:"id" gorm:"primaryKey"`
Status int8 `json:"status" binding:"omitempty,number"`
Number string `json:"number" binding:"omitempty,euDriversLicence,safe_content"`
IssuedDate time.Time `json:"issued_date" binding:"omitempty,lte"`
ExpirationDate time.Time `json:"expiration_date" binding:"omitempty,gt"`
IssuingCountry string `json:"country" binding:"safe_content"`
Categories []Category `json:"licence_categories" gorm:"many2many:licence_2_categories"`
}
type LicenceCategory struct {
ID uint `json:"id" gorm:"primaryKey"`
Category string `json:"category" binding:"safe_content"`
type Category struct {
ID uint `json:"id" gorm:"primaryKey"`
Name string `json:"category" binding:"safe_content"`
}

View File

@@ -10,31 +10,31 @@ import (
type User struct {
gorm.Model
DateOfBirth time.Time `gorm:"not null" json:"date_of_birth" binding:"required,safe_content"`
Company string `json:"company" binding:"omitempty,omitnil,safe_content"`
Phone string `json:"phone" binding:"omitempty,omitnil,safe_content"`
Notes string `json:"notes" binding:"safe_content"`
FirstName string `gorm:"not null" json:"first_name" binding:"required,safe_content"`
Password string `json:"password" binding:"required_unless=RoleID 0,safe_content"`
Email string `gorm:"unique;not null" json:"email" binding:"required,email,safe_content"`
LastName string `gorm:"not null" json:"last_name" binding:"required,safe_content"`
ProfilePicture string `json:"profile_picture" binding:"omitempty,omitnil,image,safe_content"`
Address string `gorm:"not null" json:"address" binding:"required,safe_content"`
ZipCode string `gorm:"not null" json:"zip_code" binding:"required,alphanum,safe_content"`
City string `form:"not null" json:"city" binding:"required,alphaunicode,safe_content"`
Consents []Consent `gorm:"constraint:OnUpdate:CASCADE"`
BankAccount BankAccount `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"bank_account"`
BankAccountID uint
Verification Verification `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
VerificationID uint
Membership Membership `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"membership"`
MembershipID uint
DriversLicence DriversLicence `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"drivers_licence"`
DriversLicenceID uint
ID uint `json:"id"`
PaymentStatus int8 `json:"payment_status"`
Status int8 `json:"status"`
RoleID int8 `json:"role_id"`
DateOfBirth time.Time `gorm:"not null" json:"date_of_birth" binding:"required,safe_content"`
Company string `json:"company" binding:"omitempty,omitnil,safe_content"`
Phone string `json:"phone" binding:"omitempty,omitnil,safe_content"`
Notes string `json:"notes" binding:"safe_content"`
FirstName string `gorm:"not null" json:"first_name" binding:"required,safe_content"`
Password string `json:"password" binding:"required_unless=RoleID 0,safe_content"`
Email string `gorm:"unique;not null" json:"email" binding:"required,email,safe_content"`
LastName string `gorm:"not null" json:"last_name" binding:"required,safe_content"`
ProfilePicture string `json:"profile_picture" binding:"omitempty,omitnil,image,safe_content"`
Address string `gorm:"not null" json:"address" binding:"required,safe_content"`
ZipCode string `gorm:"not null" json:"zip_code" binding:"required,alphanum,safe_content"`
City string `form:"not null" json:"city" binding:"required,alphaunicode,safe_content"`
Consents []Consent `gorm:"constraint:OnUpdate:CASCADE"`
BankAccount BankAccount `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"bank_account"`
BankAccountID uint
Verification Verification `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
VerificationID uint
Membership Membership `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"membership"`
MembershipID uint
Licence Licence `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"licence"`
LicenceID uint
ID uint `json:"id"`
PaymentStatus int8 `json:"payment_status"`
Status int8 `json:"status"`
RoleID int8 `json:"role_id"`
}
func (u *User) AfterCreate(tx *gorm.DB) (err error) {
@@ -99,14 +99,14 @@ func (u *User) Safe() map[string]interface{} {
"bic": u.BankAccount.BIC,
"mandate_reference": u.BankAccount.MandateReference,
},
"drivers_licence": map[string]interface{}{
"id": u.DriversLicence.ID,
"licence_number": u.DriversLicence.LicenceNumber,
"status": u.DriversLicence.Status,
"issued_date": u.DriversLicence.IssuedDate,
"expiration_date": u.DriversLicence.ExpirationDate,
"country": u.DriversLicence.IssuingCountry,
"licence_categories": u.DriversLicence.LicenceCategories,
"licence": map[string]interface{}{
"id": u.Licence.ID,
"number": u.Licence.Number,
"status": u.Licence.Status,
"issued_date": u.Licence.IssuedDate,
"expiration_date": u.Licence.ExpirationDate,
"country": u.Licence.IssuingCountry,
"licence_categories": u.Licence.Categories,
},
}
}

View File

@@ -1,31 +0,0 @@
package repositories
import (
"GoMembership/internal/database"
"GoMembership/internal/models"
)
type DriversLicenceInterface interface {
FindCategoryByName(categoryName string) (models.LicenceCategory, error)
FindCategoriesByIDs(ids []uint) ([]models.LicenceCategory, error)
GetAllCategories() ([]models.LicenceCategory, error)
}
type DriversLicenceRepository struct{}
func (r *DriversLicenceRepository) GetAllCategories() ([]models.LicenceCategory, error) {
var categories []models.LicenceCategory
err := database.DB.Find(&categories).Error
return categories, err
}
func (r *DriversLicenceRepository) FindCategoriesByIDs(ids []uint) ([]models.LicenceCategory, error) {
var categories []models.LicenceCategory
err := database.DB.Where("id IN ?", ids).Find(&categories).Error
return categories, err
}
func (r *DriversLicenceRepository) FindCategoryByName(categoryName string) (models.LicenceCategory, error) {
var category models.LicenceCategory
err := database.DB.Where("category = ?", categoryName).First(&category).Error
return category, err
}

View File

@@ -0,0 +1,31 @@
package repositories
import (
"GoMembership/internal/database"
"GoMembership/internal/models"
)
type LicenceInterface interface {
FindCategoryByName(categoryName string) (models.Category, error)
FindCategoriesByIDs(ids []uint) ([]models.Category, error)
GetAllCategories() ([]models.Category, error)
}
type LicenceRepository struct{}
func (r *LicenceRepository) GetAllCategories() ([]models.Category, error) {
var categories []models.Category
err := database.DB.Find(&categories).Error
return categories, err
}
func (r *LicenceRepository) FindCategoriesByIDs(ids []uint) ([]models.Category, error) {
var categories []models.Category
err := database.DB.Where("id IN ?", ids).Find(&categories).Error
return categories, err
}
func (r *LicenceRepository) FindCategoryByName(categoryName string) (models.Category, error) {
var category models.Category
err := database.DB.Where("category = ?", categoryName).First(&category).Error
return category, err
}

View File

@@ -42,7 +42,7 @@ func (ur *UserRepository) UpdateUser(user *models.User) (*models.User, error) {
err := database.DB.Transaction(func(tx *gorm.DB) error {
// Check if the user exists in the database
var existingUser models.User
if err := tx.Preload("DriversLicence.LicenceCategories").
if err := tx.Preload("Licence.Categories").
Preload("Membership").
First(&existingUser, user.ID).Error; err != nil {
return err
@@ -57,9 +57,9 @@ func (ur *UserRepository) UpdateUser(user *models.User) (*models.User, error) {
}
// Handle the update of the LicenceCategories explicitly
if user.DriversLicence.ID != 0 {
// Replace the LicenceCategories with the new list
if err := tx.Model(&existingUser.DriversLicence).Association("LicenceCategories").Replace(user.DriversLicence.LicenceCategories); err != nil {
if user.Licence.ID != 0 {
// Replace the Categories with the new list
if err := tx.Model(&existingUser.Licence).Association("Categories").Replace(user.Licence.Categories); err != nil {
return err
}
}
@@ -71,9 +71,9 @@ func (ur *UserRepository) UpdateUser(user *models.User) (*models.User, error) {
}
}
// Update the DriversLicence fields if provided
if user.DriversLicence.ID != 0 {
if err := tx.Model(&existingUser.DriversLicence).Updates(user.DriversLicence).Error; err != nil {
// Update the Licence fields if provided
if user.Licence.ID != 0 {
if err := tx.Model(&existingUser.Licence).Updates(user.Licence).Error; err != nil {
return err
}
}
@@ -86,7 +86,7 @@ func (ur *UserRepository) UpdateUser(user *models.User) (*models.User, error) {
}
var updatedUser models.User
if err := database.DB.Preload("DriversLicence.LicenceCategories").
if err := database.DB.Preload("Licence.Categories").
Preload("Membership").
First(&updatedUser, user.ID).Error; err != nil {
return nil, err
@@ -99,7 +99,7 @@ func (ur *UserRepository) GetUsers(where map[string]interface{}) (*[]models.User
result := database.DB.
Preload(clause.Associations).
Preload("Membership.SubscriptionModel").
Preload("DriversLicence.LicenceCategories").
Preload("Licence.Categories").
Where(where).Find(&users)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {
@@ -115,7 +115,7 @@ func GetUserByID(userID *uint) (*models.User, error) {
result := database.DB.
Preload(clause.Associations).
Preload("Membership.SubscriptionModel").
Preload("DriversLicence.LicenceCategories").
Preload("Licence.Categories").
First(&user, userID)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {

View File

@@ -7,7 +7,7 @@ import (
"github.com/gin-gonic/gin"
)
func RegisterRoutes(router *gin.Engine, userController *controllers.UserController, membershipcontroller *controllers.MembershipController, contactController *controllers.ContactController) {
func RegisterRoutes(router *gin.Engine, userController *controllers.UserController, membershipcontroller *controllers.MembershipController, contactController *controllers.ContactController, licenceController *controllers.LicenceController) {
router.GET("/users/verify", userController.VerifyMailHandler)
router.POST("/users/register", userController.RegisterUser)
router.POST("/users/contact", contactController.RelayContactRequest)
@@ -21,12 +21,23 @@ func RegisterRoutes(router *gin.Engine, userController *controllers.UserControll
router.POST("/v1/subscription", membershipcontroller.RegisterSubscription)
}
authRouter := router.Group("/backend/users")
authRouter.Use(middlewares.AuthMiddleware())
userRouter := router.Group("/backend/users")
userRouter.Use(middlewares.AuthMiddleware())
{
authRouter.GET("/current", userController.CurrentUserHandler)
authRouter.POST("/logout", userController.LogoutHandler)
authRouter.PATCH("/update", userController.UpdateHandler)
userRouter.GET("/current", userController.CurrentUserHandler)
userRouter.POST("/logout", userController.LogoutHandler)
userRouter.PATCH("/update", userController.UpdateHandler)
}
membershipRouter := router.Group("/backend/membership")
membershipRouter.Use(middlewares.AuthMiddleware())
{
membershipRouter.GET("/subscriptions", membershipcontroller.GetSubscriptions)
}
licenceRouter := router.Group("/backend/licence")
licenceRouter.Use(middlewares.AuthMiddleware())
{
licenceRouter.GET("/categories", licenceController.GetAllCategories)
}
}

View File

@@ -39,14 +39,15 @@ func Run() {
var subscriptionRepo repositories.SubscriptionModelsRepositoryInterface = &repositories.SubscriptionModelsRepository{}
membershipService := &services.MembershipService{Repo: membershipRepo, SubscriptionRepo: subscriptionRepo}
var licenceRepo repositories.LicenceInterface = &repositories.LicenceRepository{}
licenceService := &services.LicenceService{Repo: licenceRepo}
var userRepo repositories.UserRepositoryInterface = &repositories.UserRepository{}
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
driversLicenceService := &services.DriversLicenceService{Repo: licenceRepo}
userService := &services.UserService{Repo: userRepo, Licences: licenceRepo}
userController := &controllers.UserController{Service: userService, EmailService: emailService, ConsentService: consentService, DriversLicenceService: driversLicenceService, BankAccountService: bankAccountService, MembershipService: membershipService}
userController := &controllers.UserController{Service: userService, EmailService: emailService, ConsentService: consentService, LicenceService: licenceService, BankAccountService: bankAccountService, MembershipService: membershipService}
membershipController := &controllers.MembershipController{Service: *membershipService}
licenceController := &controllers.LicenceController{Service: *licenceService}
contactController := &controllers.ContactController{EmailService: emailService}
router := gin.Default()
@@ -63,7 +64,7 @@ func Run() {
limiter := middlewares.NewIPRateLimiter(config.Security.Ratelimits.Limit, config.Security.Ratelimits.Burst)
router.Use(middlewares.RateLimitMiddleware(limiter))
routes.RegisterRoutes(router, userController, membershipController, contactController)
routes.RegisterRoutes(router, userController, membershipController, contactController, licenceController)
validation.SetupValidators()
logger.Info.Println("Starting server on :8080")

View File

@@ -1,18 +0,0 @@
package services
import (
"GoMembership/internal/models"
"GoMembership/internal/repositories"
)
type DriversLicenceInterface interface {
GetAllCategories() ([]models.LicenceCategory, error)
}
type DriversLicenceService struct {
Repo repositories.DriversLicenceInterface
}
func (s *DriversLicenceService) GetAllCategories() ([]models.LicenceCategory, error) {
return s.Repo.GetAllCategories()
}

View File

@@ -0,0 +1,18 @@
package services
import (
"GoMembership/internal/models"
"GoMembership/internal/repositories"
)
type LicenceInterface interface {
GetAllCategories() ([]models.Category, error)
}
type LicenceService struct {
Repo repositories.LicenceInterface
}
func (s *LicenceService) GetAllCategories() ([]models.Category, error) {
return s.Repo.GetAllCategories()
}

View File

@@ -28,7 +28,7 @@ type UserServiceInterface interface {
type UserService struct {
Repo repositories.UserRepositoryInterface
Licences repositories.DriversLicenceInterface
Licences repositories.LicenceInterface
}
func (service *UserService) UpdateUser(user *models.User, userRole int8) (*models.User, error) {
@@ -38,9 +38,9 @@ func (service *UserService) UpdateUser(user *models.User, userRole int8) (*model
}
user.UpdatedAt = time.Now()
if user.DriversLicence.Status == 0 {
if user.Licence.Status == 0 {
// This is a new drivers licence
user.DriversLicence.Status = constants.UnverifiedStatus
user.Licence.Status = constants.UnverifiedStatus
}
updatedUser, err := service.Repo.UpdateUser(user)
@@ -66,7 +66,7 @@ func (service *UserService) RegisterUser(user *models.User) (uint, string, error
user.CreatedAt = time.Now()
user.UpdatedAt = time.Now()
user.PaymentStatus = constants.AwaitingPaymentStatus
user.DriversLicence.Status = constants.UnverifiedStatus
user.Licence.Status = constants.UnverifiedStatus
user.BankAccount.MandateDateSigned = time.Now()
id, err := service.Repo.CreateUser(user)

View File

@@ -6,7 +6,7 @@ import (
"github.com/go-playground/validator/v10"
)
func ValidateDriversLicence(fl validator.FieldLevel) bool {
func ValidateLicence(fl validator.FieldLevel) bool {
fieldValue := fl.Field().String()
if len(fieldValue) != 11 {
return false

View File

@@ -14,7 +14,7 @@ func SetupValidators() {
v.RegisterValidation("safe_content", ValidateSafeContent)
v.RegisterValidation("iban", IBANValidator)
v.RegisterValidation("bic", BICValidator)
v.RegisterValidation("euDriversLicence", ValidateDriversLicence)
v.RegisterValidation("euDriversLicence", ValidateLicence)
// Register struct-level validations
v.RegisterStructValidation(validateUser, models.User{})