package repositories import ( "learnsteam/cslms-api/internal/models" "gorm.io/gorm" ) type paperQuizRepository struct { DB *gorm.DB } func NewPaperQuizRepository(db *gorm.DB) PaperQuizRepository { return &paperQuizRepository{ DB: db, } } type PaperQuizRepository interface { List(int64, int, int) (*[]models.PaperQuiz, error) Total(int64) (int64, error) Find(int64) (*models.PaperQuiz, error) Update(*models.PaperQuiz) (*models.PaperQuiz, error) Delete(int64) error SumScore(int64) (float32, error) } func (r *paperQuizRepository) List(paper_id int64, page int, limit int) (*[]models.PaperQuiz, error) { var rows *[]models.PaperQuiz var err error offset := limit * (page - 1) if paper_id > 0 { err = r.DB.Offset(offset).Limit(limit).Order("vol_no ASC").Where("user_quiz_paper_id = ?", paper_id).Find(&rows).Error } else { err = r.DB.Offset(offset).Limit(limit).Find(&rows).Error } return rows, err } func (r *paperQuizRepository) Total(paper_id int64) (int64, error) { var total int64 var err error if paper_id > 0 { err = r.DB.Model(&models.PaperQuiz{}).Where("user_quiz_paper_id = ?", paper_id).Count(&total).Error } else { err = r.DB.Model(&models.PaperQuiz{}).Count(&total).Error } return total, err } func (r *paperQuizRepository) Find(id int64) (*models.PaperQuiz, error) { var row *models.PaperQuiz err := r.DB.Where("id = ?", id).First(&row).Error return row, err } func (r *paperQuizRepository) Update(quiz *models.PaperQuiz) (*models.PaperQuiz, error) { var row *models.PaperQuiz if err := r.DB.Where("id=?", quiz.ID).First(&row).Error; err != nil { return nil, err } err := r.DB.Model(&row).Select("*").Updates(&quiz).Error return row, err } func (r *paperQuizRepository) Delete(id int64) error { var row *models.PaperQuiz if err := r.DB.Where("id=?", id).First(&row).Error; err != nil { return err } err := r.DB.Delete(&row).Error return err } func (r *paperQuizRepository) SumScore(paper_id int64) (float32, error) { var result struct { Score float32 } if err := r.DB.Model(&models.PaperQuiz{}).Select("SUM(score) AS score"). Where("user_quiz_paper_id = ?", paper_id). Scan(&result).Error; err != nil { return 0, err } return result.Score, nil }