63 lines
1.7 KiB
Go
63 lines
1.7 KiB
Go
package routes
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.artlef.fr/bibliomane/internal/appcontext"
|
|
"git.artlef.fr/bibliomane/internal/i18nresource"
|
|
"git.artlef.fr/bibliomane/internal/model"
|
|
"git.artlef.fr/bibliomane/internal/myvalidator"
|
|
"git.artlef.fr/bibliomane/internal/query"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func DeleteCollectionBookHandler(ac appcontext.AppContext) {
|
|
collectionItemId, 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 collectionItem model.CollectionItem
|
|
err = ac.Db.First(&collectionItem, collectionItemId).Error
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
collection, err := query.FetchCollectionHeaderFromItem(ac.Db, collectionItem.ID)
|
|
|
|
if collection.UserID != user.ID {
|
|
err := myvalidator.HttpError{
|
|
StatusCode: http.StatusUnauthorized,
|
|
Err: errors.New(i18nresource.GetTranslatedMessage(&ac, "Unauthorized")),
|
|
}
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
err = ac.Db.Delete(&collectionItem).Error
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
|
|
//update position on remaining items
|
|
q := ac.Db.Model(&model.CollectionItem{})
|
|
q = q.Where("collection_id = ? AND position > ?", collectionItem.CollectionID, collectionItem.Position)
|
|
err = q.UpdateColumn("position", gorm.Expr("position - 1")).Error
|
|
if err != nil {
|
|
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
|
|
return
|
|
}
|
|
ac.C.JSON(http.StatusOK, "Success")
|
|
}
|