书籍列表接口新增参数

This commit is contained in:
2025-08-13 15:19:42 +08:00
parent 6ccc87f2bf
commit 8afe651c64
201 changed files with 6987 additions and 1066 deletions

View File

@ -232,6 +232,9 @@ func (s *sBook) AppList(ctx context.Context, in *model.BookAppListIn) (out *mode
if in.IsFeatured {
m = m.Where(dao.Books.Columns().IsFeatured, 1)
}
if in.IsHot {
m = m.Where(dao.Books.Columns().IsHot, 1)
}
if in.Sort != "" {
m = m.Order(in.Sort)
}
@ -278,6 +281,30 @@ func (s *sBook) AppList(ctx context.Context, in *model.BookAppListIn) (out *mode
out.List[i].MyRating = 0
}
}
// 查询用户书架
type shelfRow struct {
BookId int64 `json:"bookId"`
}
shelves := make([]shelfRow, 0)
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
WhereIn(dao.Bookshelves.Columns().BookId, bookIds).
Scan(&shelves)
if err == nil && len(shelves) > 0 {
shelfMap := make(map[int64]bool, len(shelves))
for _, s := range shelves {
shelfMap[s.BookId] = true
}
for i := range out.List {
out.List[i].IsInBookshelf = shelfMap[out.List[i].Id]
}
} else {
for i := range out.List {
out.List[i].IsInBookshelf = false
}
}
}
return out, nil
@ -323,7 +350,7 @@ func (s *sBook) AppRate(ctx context.Context, in *model.BookAppRateIn) (out *mode
// 开启事务处理评分
if err := dao.BookRatings.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
// 检查是否已经评分过
exist, err := dao.BookRatings.Ctx(ctx).TX(tx).
exist, err := dao.BookRatings.Ctx(ctx).
Where(dao.BookRatings.Columns().UserId, in.UserId).
Where(dao.BookRatings.Columns().BookId, in.BookId).
Exist()
@ -333,7 +360,7 @@ func (s *sBook) AppRate(ctx context.Context, in *model.BookAppRateIn) (out *mode
if exist {
// 更新现有评分
_, err = dao.BookRatings.Ctx(ctx).TX(tx).
_, err = dao.BookRatings.Ctx(ctx).
Where(dao.BookRatings.Columns().UserId, in.UserId).
Where(dao.BookRatings.Columns().BookId, in.BookId).
Data(do.BookRatings{
@ -344,7 +371,7 @@ func (s *sBook) AppRate(ctx context.Context, in *model.BookAppRateIn) (out *mode
}
} else {
// 创建新评分记录
_, err = dao.BookRatings.Ctx(ctx).TX(tx).Data(do.BookRatings{
_, err = dao.BookRatings.Ctx(ctx).Data(do.BookRatings{
UserId: in.UserId,
BookId: in.BookId,
Score: in.Rating,
@ -355,20 +382,22 @@ func (s *sBook) AppRate(ctx context.Context, in *model.BookAppRateIn) (out *mode
}
// 重新计算书籍平均评分
var avgRating float64
err = dao.BookRatings.Ctx(ctx).TX(tx).
var result struct {
AvgRating float64 `json:"avg_rating"`
}
err = dao.BookRatings.Ctx(ctx).
Where(dao.BookRatings.Columns().BookId, in.BookId).
Fields("AVG(score) as avg_rating").
Scan(&avgRating)
Fields("COALESCE(AVG(" + dao.BookRatings.Columns().Score + "), 0) as avg_rating").
Scan(&result)
if err != nil {
return ecode.Fail.Sub("rating_calculation_failed")
}
// 更新书籍的平均评分
_, err = dao.Books.Ctx(ctx).TX(tx).
_, err = dao.Books.Ctx(ctx).
Where(dao.Books.Columns().Id, in.BookId).
Data(do.Books{
Rating: avgRating,
Rating: result.AvgRating,
}).Update()
if err != nil {
return ecode.Fail.Sub("book_rating_update_failed")
@ -397,7 +426,7 @@ func (s *sBook) AppDetail(ctx context.Context, in *model.BookAppDetailIn) (out *
m = m.Where(dao.Books.Columns().Id, in.Id)
// 执行查询
if err = m.Scan(out); err != nil {
if err = m.WithAll().Scan(out); err != nil {
return nil, ecode.Fail.Sub("book_query_failed")
}
@ -408,6 +437,29 @@ func (s *sBook) AppDetail(ctx context.Context, in *model.BookAppDetailIn) (out *
// 如果用户已登录,查询阅读进度
if in.UserId > 0 {
// 查询用户是否已将本书加入书架
count, err := dao.Bookshelves.Ctx(ctx).
Where(dao.Bookshelves.Columns().UserId, in.UserId).
Where(dao.Bookshelves.Columns().BookId, in.Id).
Count()
if err == nil {
out.IsInBookshelf = count > 0
}
// 查询用户是否已评分
var ratingRecord struct {
Score float64 `json:"score"`
}
err = dao.BookRatings.Ctx(ctx).
Fields("score").
Where(dao.BookRatings.Columns().UserId, in.UserId).
Where(dao.BookRatings.Columns().BookId, in.Id).
Scan(&ratingRecord)
if err == nil && ratingRecord.Score > 0 {
out.HasRated = true
out.MyRating = ratingRecord.Score
}
// 查询用户对该书籍的历史记录
var historyRecord struct {
ChapterId int64 `json:"chapterId"`
@ -435,7 +487,7 @@ func (s *sBook) AppDetail(ctx context.Context, in *model.BookAppDetailIn) (out *
readChapters, err := dao.UserReadRecords.Ctx(ctx).
Where(dao.UserReadRecords.Columns().UserId, in.UserId).
Where(dao.UserReadRecords.Columns().BookId, in.Id).
Where(dao.UserReadRecords.Columns().ChapterId, ">", 0). // 只统计有章节ID的记录
WhereGT(dao.UserReadRecords.Columns().ChapterId, 0). // 只统计有章节ID的记录
Count()
if err == nil {
@ -454,274 +506,174 @@ func (s *sBook) AppDetail(ctx context.Context, in *model.BookAppDetailIn) (out *
func (s *sBook) MyList(ctx context.Context, in *model.MyBookListIn) (out *model.MyBookListOut, err error) {
out = &model.MyBookListOut{}
// 验证用户ID
if in.UserId == 0 {
return nil, ecode.Fail.Sub("user_id_required")
}
// 验证类型参数
if in.Type < 1 || in.Type > 3 {
return nil, ecode.Fail.Sub("type_invalid")
}
var list []model.MyBookItem
var total int
var (
ids []int64
extraMap map[int64]struct {
Progress int
LastReadAt string
}
total int
)
switch in.Type {
case 1: // 正在读
// 查询书架表中read_status=1的记录
case 1, 2:
var bookshelves []struct {
BookId int64 `json:"bookId"`
LastReadPercent float64 `json:"lastReadPercent"`
LastReadAt string `json:"lastReadAt"`
}
if in.Sort != "" {
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id, last_read_percent, last_read_at").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
Where(dao.Bookshelves.Columns().ReadStatus, 1).
Order(in.Sort).
Page(in.Page, in.Size).
ScanAndCount(&bookshelves, &total, false)
} else {
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id, last_read_percent, last_read_at").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
Where(dao.Bookshelves.Columns().ReadStatus, 1).
Page(in.Page, in.Size).
ScanAndCount(&bookshelves, &total, false)
readStatus := 1
if in.Type == 2 {
readStatus = 2
}
q := dao.Bookshelves.Ctx(ctx).
Fields("book_id, last_read_percent, last_read_at").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
Where(dao.Bookshelves.Columns().ReadStatus, readStatus)
if in.Sort != "" {
q = q.Order(in.Sort)
} else {
q = q
}
err = q.Page(in.Page, in.Size).ScanAndCount(&bookshelves, &total, false)
if err != nil {
return nil, ecode.Fail.Sub("bookshelf_query_failed")
}
// 获取书籍详细信息
if len(bookshelves) > 0 {
bookIds := make([]int64, 0, len(bookshelves))
for _, bs := range bookshelves {
bookIds = append(bookIds, bs.BookId)
}
var books []model.Book
err = dao.Books.Ctx(ctx).
WhereIn(dao.Books.Columns().Id, bookIds).
Scan(&books)
if err != nil {
return nil, ecode.Fail.Sub("book_query_failed")
}
// 构建书籍ID到书架信息的映射
bookshelfMap := make(map[int64]struct {
LastReadPercent float64
LastReadAt string
})
for _, bs := range bookshelves {
bookshelfMap[bs.BookId] = struct {
LastReadPercent float64
LastReadAt string
}{
LastReadPercent: bs.LastReadPercent,
LastReadAt: bs.LastReadAt,
}
}
// 构建返回列表
for _, book := range books {
bsInfo := bookshelfMap[book.Id]
list = append(list, model.MyBookItem{
Id: book.Id,
Title: book.Title,
CoverUrl: book.CoverUrl,
Description: book.Description,
Progress: int(bsInfo.LastReadPercent),
IsInShelf: true,
LastReadAt: bsInfo.LastReadAt,
Status: book.Status,
AuthorId: book.AuthorId,
CategoryId: book.CategoryId,
})
ids = make([]int64, 0, len(bookshelves))
extraMap = make(map[int64]struct {
Progress int
LastReadAt string
}, len(bookshelves))
for _, bs := range bookshelves {
ids = append(ids, bs.BookId)
extraMap[bs.BookId] = struct {
Progress int
LastReadAt string
}{
Progress: int(bs.LastReadPercent),
LastReadAt: bs.LastReadAt,
}
}
case 2: // 已读完
// 查询书架表中read_status=2的记录
var bookshelves []struct {
BookId int64 `json:"bookId"`
LastReadPercent float64 `json:"lastReadPercent"`
LastReadAt string `json:"lastReadAt"`
}
if in.Sort != "" {
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id, last_read_percent, last_read_at").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
Where(dao.Bookshelves.Columns().ReadStatus, 2).
Order(in.Sort).
Page(in.Page, in.Size).
ScanAndCount(&bookshelves, &total, false)
} else {
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id, last_read_percent, last_read_at").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
Where(dao.Bookshelves.Columns().ReadStatus, 2).
Page(in.Page, in.Size).
ScanAndCount(&bookshelves, &total, false)
}
if err != nil {
return nil, ecode.Fail.Sub("bookshelf_query_failed")
}
// 获取书籍详细信息
if len(bookshelves) > 0 {
bookIds := make([]int64, 0, len(bookshelves))
for _, bs := range bookshelves {
bookIds = append(bookIds, bs.BookId)
}
var books []model.Book
err = dao.Books.Ctx(ctx).
WhereIn(dao.Books.Columns().Id, bookIds).
Scan(&books)
if err != nil {
return nil, ecode.Fail.Sub("book_query_failed")
}
// 构建书籍ID到书架信息的映射
bookshelfMap := make(map[int64]struct {
LastReadPercent float64
LastReadAt string
})
for _, bs := range bookshelves {
bookshelfMap[bs.BookId] = struct {
LastReadPercent float64
LastReadAt string
}{
LastReadPercent: bs.LastReadPercent,
LastReadAt: bs.LastReadAt,
}
}
// 构建返回列表
for _, book := range books {
bsInfo := bookshelfMap[book.Id]
list = append(list, model.MyBookItem{
Id: book.Id,
Title: book.Title,
CoverUrl: book.CoverUrl,
Description: book.Description,
Progress: int(bsInfo.LastReadPercent),
IsInShelf: true,
LastReadAt: bsInfo.LastReadAt,
Status: book.Status,
AuthorId: book.AuthorId,
CategoryId: book.CategoryId,
})
}
}
case 3: // 历史记录
// 查询user_read_history表
case 3:
var histories []struct {
BookId int64 `json:"bookId"`
ChapterId int64 `json:"chapterId"`
ReadAt string `json:"readAt"`
}
q := dao.UserReadHistory.Ctx(ctx).
Fields("book_id, chapter_id, read_at").
Where(dao.UserReadHistory.Columns().UserId, in.UserId)
if in.Sort != "" {
err = dao.UserReadHistory.Ctx(ctx).
Fields("book_id, chapter_id, read_at").
Where(dao.UserReadHistory.Columns().UserId, in.UserId).
Order(in.Sort).
Page(in.Page, in.Size).
ScanAndCount(&histories, &total, false)
q = q.Order(in.Sort)
} else {
err = dao.UserReadHistory.Ctx(ctx).
Fields("book_id, chapter_id, read_at").
Where(dao.UserReadHistory.Columns().UserId, in.UserId).
OrderDesc(dao.UserReadHistory.Columns().ReadAt).
Page(in.Page, in.Size).
ScanAndCount(&histories, &total, false)
q = q.OrderDesc(dao.UserReadHistory.Columns().ReadAt)
}
err = q.Page(in.Page, in.Size).ScanAndCount(&histories, &total, false)
if err != nil {
return nil, ecode.Fail.Sub("history_query_failed")
}
// 获取书籍详细信息
if len(histories) > 0 {
bookIds := make([]int64, 0, len(histories))
for _, history := range histories {
bookIds = append(bookIds, history.BookId)
}
var books []model.Book
err = dao.Books.Ctx(ctx).
WhereIn(dao.Books.Columns().Id, bookIds).
Scan(&books)
if err != nil {
return nil, ecode.Fail.Sub("book_query_failed")
}
// 构建书籍ID到历史信息的映射
historyMap := make(map[int64]struct {
ChapterId int64
ReadAt string
})
for _, history := range histories {
historyMap[history.BookId] = struct {
ChapterId int64
ReadAt string
}{
ChapterId: history.ChapterId,
ReadAt: history.ReadAt,
}
}
// 检查是否在书架中
var bookshelves []struct {
BookId int64 `json:"bookId"`
}
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
WhereIn(dao.Bookshelves.Columns().BookId, bookIds).
Scan(&bookshelves)
if err != nil {
return nil, ecode.Fail.Sub("bookshelf_query_failed")
}
// 构建书架ID集合
shelfBookIds := make(map[int64]bool)
for _, bs := range bookshelves {
shelfBookIds[bs.BookId] = true
}
// 构建返回列表
for _, book := range books {
historyInfo := historyMap[book.Id]
list = append(list, model.MyBookItem{
Id: book.Id,
Title: book.Title,
CoverUrl: book.CoverUrl,
Description: book.Description,
Progress: 0, // 历史记录不显示进度
IsInShelf: shelfBookIds[book.Id],
LastReadAt: historyInfo.ReadAt,
Status: book.Status,
AuthorId: book.AuthorId,
CategoryId: book.CategoryId,
})
ids = make([]int64, 0, len(histories))
extraMap = make(map[int64]struct {
Progress int
LastReadAt string
}, len(histories))
for _, h := range histories {
ids = append(ids, h.BookId)
extraMap[h.BookId] = struct {
Progress int
LastReadAt string
}{
Progress: 0,
LastReadAt: h.ReadAt,
}
}
default:
// 返回空列表
}
out = &model.MyBookListOut{
Total: total,
List: list,
var books []model.MyBookItem
if len(ids) > 0 {
err = dao.Books.Ctx(ctx).WhereIn(dao.Books.Columns().Id, ids).Scan(&books)
if err != nil {
return nil, ecode.Fail.Sub("book_query_failed")
}
}
// type3 需要查书架
shelfBookIds := map[int64]bool{}
if in.Type == 3 && len(ids) > 0 {
var bookshelves []struct{ BookId int64 }
err = dao.Bookshelves.Ctx(ctx).
Fields("book_id").
Where(dao.Bookshelves.Columns().UserId, in.UserId).
WhereIn(dao.Bookshelves.Columns().BookId, ids).
Scan(&bookshelves)
if err != nil {
return nil, ecode.Fail.Sub("bookshelf_query_failed")
}
for _, bs := range bookshelves {
shelfBookIds[bs.BookId] = true
}
}
for i := range books {
if info, ok := extraMap[books[i].Id]; ok {
books[i].Progress = info.Progress
books[i].LastReadAt = info.LastReadAt
}
if in.Type == 1 || in.Type == 2 {
books[i].IsInShelf = true
} else if in.Type == 3 {
books[i].IsInShelf = shelfBookIds[books[i].Id]
}
}
// 查询用户评分信息
if len(books) > 0 {
bookIds := make([]int64, 0, len(books))
for _, book := range books {
bookIds = append(bookIds, book.Id)
}
type ratingRow struct {
BookId int64 `json:"bookId"`
Score float64 `json:"score"`
}
ratings := make([]ratingRow, 0)
err = dao.BookRatings.Ctx(ctx).
Fields("book_id, score").
Where(dao.BookRatings.Columns().UserId, in.UserId).
WhereIn(dao.BookRatings.Columns().BookId, bookIds).
Scan(&ratings)
if err == nil && len(ratings) > 0 {
ratingMap := make(map[int64]float64, len(ratings))
for _, r := range ratings {
ratingMap[r.BookId] = r.Score
}
for i := range books {
if score, ok := ratingMap[books[i].Id]; ok {
books[i].HasRated = true
books[i].MyRating = score
} else {
books[i].HasRated = false
books[i].MyRating = 0
}
}
} else {
for i := range books {
books[i].HasRated = false
books[i].MyRating = 0
}
}
}
out.Total = total
out.List = books
return
}
@ -762,3 +714,22 @@ func (s *sBook) SetRecommended(ctx context.Context, in *model.BookSetRecommended
}
return &model.BookCRUDOut{Success: true}, nil
}
// SetHot: 单独修改书籍的热门状态
func (s *sBook) SetHot(ctx context.Context, in *model.BookSetHotIn) (out *model.BookCRUDOut, err error) {
// 检查书籍是否存在
exist, err := dao.Books.Ctx(ctx).WherePri(in.Id).Exist()
if err != nil {
return nil, ecode.Fail.Sub("book_query_failed")
}
if !exist {
return nil, ecode.NotFound.Sub("book_not_found")
}
_, err = dao.Books.Ctx(ctx).WherePri(in.Id).Data(do.Books{
IsHot: in.IsHot,
}).Update()
if err != nil {
return nil, ecode.Fail.Sub("book_update_failed")
}
return &model.BookCRUDOut{Success: true}, nil
}