-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlater.txt
More file actions
236 lines (199 loc) · 7.45 KB
/
later.txt
File metadata and controls
236 lines (199 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
type BoughtChapterManager struct {
Model models.BoughtChapter
ModelList []models.BoughtChapter
}
func (b BoughtChapterManager) GetBoughtChapters(db *gorm.DB, buyer *models.User, book *models.Book) []models.Chapter {
boughtChapters := b.ModelList
chapters := []models.Chapter{}
if !buyer.SubscriptionExpired() {
db.Where("book_id = ?", book.ID).Find(&chapters)
} else {
db.Joins("JOIN chapters ON chapters.id = bought_chapters.chapter_id").Where("bought_chapters.buyer_id = ? AND chapters.book_id = ?", buyer.ID, book.ID).Scopes(scopes.BoughtChapterScope).Find(&boughtChapters)
for i := range boughtChapters {
chapters = append(chapters, boughtChapters[i].Chapter)
}
}
if len(chapters) == 0 {
// If the user hasn't bought any, he should see the first chapter for free
chapters = book.Chapters[:1]
}
return chapters
}
func (b BoughtChapterManager) GetBoughtBooks(db *gorm.DB, buyer *models.User) []models.Book {
// Return books in which the user has bought at least a chapter
books := []models.Book{}
subQuery := db.Model(&BoughtChapterManager{}).Select("chapter_id").Where("user_id = ?", buyer.ID)
// Main query to find all books that have at least one chapter in the subquery
db.Model(&models.Book{}).
Joins("JOIN chapters ON chapters.book_id = books.id").
Where("chapters.id IN (?)", subQuery).
Distinct("books.*"). // To ensure unique book s
Scopes(scopes.AuthorGenreTagReviewsBookScope).
Find(&books)
return books
}
func (b BoughtChapterManager) CheckAllChaptersBought(db *gorm.DB, buyer *models.User, book *models.Book) bool {
var chapterIDs []uuid.UUID
for _, chapter := range book.Chapters {
chapterIDs = append(chapterIDs, chapter.ID)
}
var count int64
db.Model(&models.BoughtChapter{}).
Where("buyer_id = ? AND chapter_id IN ?", buyer.ID, chapterIDs).
Group("buyer_id").
Having("COUNT(DISTINCT chapter_id) = ?", len(chapterIDs)).
Count(&count)
return count > 0
}
func (b BoughtChapterManager) CheckIfAtLeastAChapterWasBought(db *gorm.DB, buyer *models.User, book models.Book) bool {
var chapterIDs []uuid.UUID
for _, chapter := range book.Chapters {
chapterIDs = append(chapterIDs, chapter.ID)
}
var boughtChaptersCount int64
db.Model(&models.BoughtChapter{}).Where("chapter_id IN ?", chapterIDs).Count(&boughtChaptersCount)
return boughtChaptersCount > 0
}
func (b BoughtChapterManager) GetByBuyerAndChapter(db *gorm.DB, buyer *models.User, chapter models.Chapter) *models.BoughtChapter {
boughtChapter := models.BoughtChapter{
BuyerID: buyer.ID,
ChapterID: chapter.ID,
}
db.Joins("Chapter").Take(&boughtChapter, boughtChapter)
if boughtChapter.ID == uuid.Nil {
return nil
}
return &boughtChapter
}
func (b BoughtChapterManager) BuyAChapter(db *gorm.DB, buyer *models.User, book *models.Book) models.BoughtChapter {
// Get the chapter that the user doesn't have yet
nextChapter := models.Chapter{}
subQuery := db.Model(&models.BoughtChapter{}).Select("chapter_id").Where("buyer_id = ?", buyer.ID)
db.Model(&models.Chapter{}).
Where("book_id = ? AND id NOT IN (?)", book.ID, subQuery).
Order("created_at ASC"). // Assuming chapters are ordered by created_at descending order
First(&nextChapter)
secondChapter := models.Chapter{}
bookChapters := book.Chapters
if len(bookChapters) > 1 {
firstChapter := bookChapters[0]
if firstChapter.ID == nextChapter.ID {
// Get second chapter
secondChapter = bookChapters[1]
}
}
boughtChapters := []models.BoughtChapter{{
BuyerID: buyer.ID,
ChapterID: nextChapter.ID,
Chapter: nextChapter,
}}
if secondChapter.ID != uuid.Nil {
// Add second chapter too
secondBoughtChapter := models.BoughtChapter{
BuyerID: buyer.ID,
ChapterID: secondChapter.ID,
Chapter: secondChapter,
}
boughtChapters = append(boughtChapters, secondBoughtChapter)
}
db.Create(&boughtChapters)
chapterPrice := book.ChapterPrice
// Move coins from buyer to author
buyer.Coins = buyer.Coins - chapterPrice
db.Save(&buyer)
// Increase user coins
author := book.Author
author.Coins = author.Coins + chapterPrice
db.Save(&author)
return boughtChapters[len(boughtChapters)-1]
}
func (b BoughtChapterManager) BuyWholeBook(db *gorm.DB, buyer *models.User, book models.Book) models.Book {
chaptersToBuy := []models.BoughtChapter{}
for _, chapter := range book.Chapters {
chapterToBuy := models.BoughtChapter{
BuyerID: buyer.ID,
ChapterID: chapter.ID,
Chapter: chapter,
}
chaptersToBuy = append(chaptersToBuy, chapterToBuy)
}
db.Clauses(clause.OnConflict{
DoNothing: true,
}).Create(&chaptersToBuy)
bookPrice := book.FullPrice
// Move coins from buyer to author
buyer.Coins = buyer.Coins - *bookPrice
db.Save(&buyer)
// Increase user coins
author := book.Author
author.Coins = author.Coins + *bookPrice
db.Save(&author)
return book
}
// @Summary Buy A Chapter Of A Book
// @Description `This endpoint allows a user to buy the next chapter of a book.`
// @Description `It happens in sequence. 1, 2, 3, 4 etc. That means if a user has bought chapter 2 before. This endpoint will buy chapter 3`
// @Tags Books
// @Param slug path string true "Book slug"
// @Success 201 {object} schemas.BookResponseSchema
// @Failure 400 {object} utils.ErrorResponse
// @Router /books/book/{slug}/buy-chapter [get]
// @Security BearerAuth
func (ep Endpoint) BuyAChapter(c *fiber.Ctx) error {
db := ep.DB
user := RequestUser(c)
book, err := bookManager.GetContractedBookBySlug(db, c.Params("slug"))
if err != nil {
return c.Status(404).JSON(err)
}
if user.ID == book.AuthorID {
return c.Status(400).JSON(utils.RequestErr(utils.ERR_NOT_ALLOWED, "You can't buy chapter of your own book"))
}
bookAlreadyBought := boughtChapterManager.CheckAllChaptersBought(db, user, book)
if bookAlreadyBought {
return c.Status(400).JSON(utils.RequestErr(utils.ERR_ALREADY_BOUGHT, "You have bought all the chapters of this book already"))
}
if book.ChapterPrice > user.Coins {
return c.Status(401).JSON(utils.RequestErr(utils.ERR_INSUFFICIENT_COINS, "You have insufficient coins"))
}
// Create bought chapter
boughtChapter := boughtChapterManager.BuyAChapter(db, user, book)
// Create and send notification in socket
notification := notificationManager.Create(
db, user, book.Author, choices.NT_BOOK_PURCHASE,
fmt.Sprintf("%s bought one of your books.", user.Username),
book, nil, nil, nil,
)
SendNotificationInSocket(c, notification)
response := schemas.ChapterResponseSchema{
ResponseSchema: ResponseMessage("Chapter bought successfully"),
Data: schemas.ChapterSchema{}.Init(boughtChapter.Chapter),
}
return c.Status(201).JSON(response)
}
// @Summary View Bought Books
// @Description This endpoint returns all books in which a user has bought at least a chapter
// @Tags Books
// @Param page query int false "Current Page" default(1)
// @Success 200 {object} schemas.BooksResponseSchema
// @Failure 400 {object} utils.ErrorResponse
// @Router /books/bought [get]
// @Security BearerAuth
func (ep Endpoint) GetBoughtBooks(c *fiber.Ctx) error {
db := ep.DB
user := RequestUser(c)
books := boughtChapterManager.GetBoughtBooks(db, user)
// Paginate and return books
paginatedData, paginatedBooks, err := PaginateQueryset(books, c, 200)
if err != nil {
return c.Status(400).JSON(err)
}
books = paginatedBooks.([]models.Book)
response := schemas.BooksResponseSchema{
ResponseSchema: ResponseMessage("Books fetched successfully"),
Data: schemas.BooksResponseDataSchema{
PaginatedResponseDataSchema: *paginatedData,
}.Init(books),
}
return c.Status(200).JSON(response)
}