73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package routes
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.artlef.fr/bibliomane/internal/appcontext"
|
|
"git.artlef.fr/bibliomane/internal/dto"
|
|
"git.artlef.fr/bibliomane/internal/i18nresource"
|
|
"git.artlef.fr/bibliomane/internal/model"
|
|
"git.artlef.fr/bibliomane/internal/myvalidator"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func PostCollectionBookHandler(ac appcontext.AppContext) {
|
|
collectionId, err := strconv.ParseUint(ac.C.Param("id"), 10, 64)
|
|
if err != nil {
|
|
ac.C.JSON(http.StatusBadRequest, gin.H{"error": err})
|
|
return
|
|
}
|
|
|
|
user, err := ac.GetAuthenticatedUser()
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
var collection model.Collection
|
|
err = ac.Db.First(&collection, collectionId).Error
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
if collection.UserID != user.ID {
|
|
err := myvalidator.HttpError{
|
|
StatusCode: http.StatusUnauthorized,
|
|
Err: errors.New(i18nresource.GetTranslatedMessage(&ac, "Unauthorized")),
|
|
}
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
var collectionBook dto.CollectionBook
|
|
err = ac.C.ShouldBindJSON(&collectionBook)
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
var book model.Book
|
|
err = ac.Db.First(&book, collectionBook.BookID).Error
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
//reorder other items
|
|
q := ac.Db.Model(&model.CollectionItem{})
|
|
q = q.Where("collection_id = ?", collection.ID)
|
|
err = q.UpdateColumn("position", gorm.Expr("position + 1")).Error
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
item := model.CollectionItem{Position: 1, BookID: book.ID, CollectionID: collection.ID}
|
|
ac.Db.Save(&item)
|
|
ac.C.String(http.StatusOK, "Success")
|
|
}
|