package repositories import ( "fmt" "learnsteam/cslms-api/internal/models" "gorm.io/gorm" ) type userRepository struct { DB *gorm.DB } func NewUserRepository(db *gorm.DB) UserRepository { return &userRepository{ DB: db, } } type UserRepository interface { List(string, int, int) (*[]models.User, error) Total(string) (int64, error) Find(int64) (*models.User, error) FindByUsername(string) (*models.User, error) Create(*models.User) (*models.User, error) Update(*models.User) (*models.User, error) Delete(string) error } func (r *userRepository) List(q string, page int, limit int) (*[]models.User, error) { var users *[]models.User var err error offset := limit * (page - 1) fmt.Println("q", q) if q != "" { err = r.DB.Offset(offset).Limit(limit).Order("last_name ASC, first_name ASC").Where("user_role = ?", "member").Where("name LIKE ? OR user_name LIKE ?", "%"+q+"%", "%"+q+"%").Find(&users).Error } else { fmt.Println(" query") err = r.DB.Offset(offset).Limit(limit).Order("last_name ASC, first_name ASC").Where("user_role = ?", "member").Find(&users).Error } return users, err } func (r *userRepository) Total(q string) (int64, error) { var total int64 var err error if q != "" { err = r.DB.Model(&models.User{}).Where("user_role = ?", "member").Where("name LIKE ? OR user_name LIKE ?", "%"+q+"%", "%"+q+"%").Count(&total).Error } else { err = r.DB.Model(&models.User{}).Where("user_role = ?", "member").Count(&total).Error } return total, err } func (r *userRepository) Find(id int64) (*models.User, error) { var user *models.User err := r.DB.Where("id = ?", id).First(&user).Error return user, err } func (r *userRepository) FindByUsername(username string) (*models.User, error) { var user *models.User err := r.DB.Where("user_name = ?", username).First(&user).Error return user, err } func (r *userRepository) Create(user *models.User) (*models.User, error) { err := r.DB.Create(&user).Error return user, err } func (r *userRepository) Update(user *models.User) (*models.User, error) { var row *models.User if err := r.DB.Where("id=?", user.ID).First(&row).Error; err != nil { return nil, err } err := r.DB.Model(&row).Select("*").Updates(&user).Error return row, err } func (r *userRepository) Delete(id string) error { var user *models.User if err := r.DB.Where("id=?", id).First(&user).Error; err != nil { return err } err := r.DB.Delete(&user).Error return err }