67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package models
|
|
|
|
import (
|
|
"GoMembership/pkg/logger"
|
|
"fmt"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Licence struct {
|
|
ID uint `json:"id"`
|
|
UserID uint `json:"user_id"`
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
Status int8 `json:"status" binding:"omitempty,number"`
|
|
Number string `json:"number" binding:"omitempty,safe_content"`
|
|
IssuedDate time.Time `json:"issued_date" binding:"omitempty"`
|
|
ExpirationDate time.Time `json:"expiration_date" binding:"omitempty"`
|
|
IssuingCountry string `json:"country" binding:"safe_content"`
|
|
Categories []*Category `json:"categories" gorm:"many2many:licence_2_categories"`
|
|
}
|
|
|
|
func (l *Licence) BeforeSafe(tx *gorm.DB) error {
|
|
if err := tx.Model(l).Association("Categories").Replace(l.Categories); err != nil {
|
|
return fmt.Errorf("failed to link categories: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (l *Licence) Create(db *gorm.DB) error {
|
|
if err := db.Omit("Categories").Create(l).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := db.Model(&l).Association("Categories").Replace(l.Categories); err != nil {
|
|
return err
|
|
}
|
|
|
|
logger.Info.Printf("Licence created: %#v", l)
|
|
return db.Preload("Categories").First(l, l.ID).Error // Refresh the object with Categories
|
|
}
|
|
|
|
func (l *Licence) Update(db *gorm.DB) error {
|
|
|
|
return db.Transaction(func(tx *gorm.DB) error {
|
|
// Check if the user exists in the database
|
|
var existingLicence Licence
|
|
|
|
logger.Info.Printf("updating Licence: %#v", l)
|
|
if err := tx.First(&existingLicence, l.ID).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := tx.Model(&existingLicence).Updates(l).Error; err != nil {
|
|
return err
|
|
}
|
|
return tx.First(l, l.ID).Error
|
|
})
|
|
|
|
}
|
|
|
|
func (l *Licence) Delete(db *gorm.DB) error {
|
|
return db.Delete(&l).Error
|
|
}
|