2022-01-25 05:22:33 +00:00
|
|
|
package databag
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"databag/internal/store"
|
|
|
|
)
|
|
|
|
|
|
|
|
func SetCardGroup(w http.ResponseWriter, r *http.Request) {
|
|
|
|
account, code, err := BearerAppToken(r, false);
|
|
|
|
if err != nil {
|
|
|
|
ErrResponse(w, code, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// scan parameters
|
|
|
|
params := mux.Vars(r)
|
|
|
|
cardId := params["cardId"]
|
|
|
|
groupId := params["groupId"]
|
|
|
|
|
|
|
|
// load referenced card
|
2022-02-03 06:13:46 +00:00
|
|
|
var slot store.CardSlot
|
|
|
|
if err := store.DB.Preload("Card").Where("account_id = ? AND card_slot_id = ?", account.ID, cardId).First(&slot).Error; err != nil {
|
|
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
2022-01-25 05:22:33 +00:00
|
|
|
ErrResponse(w, http.StatusNotFound, err)
|
2022-02-03 06:13:46 +00:00
|
|
|
} else {
|
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
2022-01-25 05:22:33 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2022-02-03 06:13:46 +00:00
|
|
|
if slot.Card == nil {
|
|
|
|
ErrResponse(w, http.StatusNotFound, errors.New("card has been deleted"))
|
|
|
|
return
|
|
|
|
}
|
2022-01-25 05:22:33 +00:00
|
|
|
|
|
|
|
// load referenced group
|
|
|
|
var group store.Group
|
|
|
|
if err := store.DB.Where("account_id = ? AND group_id = ?", account.ID, groupId).First(&group).Error; err != nil {
|
|
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
|
|
|
} else {
|
|
|
|
ErrResponse(w, http.StatusNotFound, err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// save and update revision
|
2022-02-03 06:13:46 +00:00
|
|
|
slot.Card.Groups = append(slot.Card.Groups, group)
|
|
|
|
slot.Card.ViewRevision += 1
|
|
|
|
slot.Revision = account.CardRevision + 1
|
2022-01-25 05:22:33 +00:00
|
|
|
err = store.DB.Transaction(func(tx *gorm.DB) error {
|
2022-01-25 07:25:43 +00:00
|
|
|
if res := tx.Model(&account).Update("card_revision", account.CardRevision + 1).Error; res != nil {
|
2022-01-25 05:22:33 +00:00
|
|
|
return res
|
|
|
|
}
|
2022-02-03 06:13:46 +00:00
|
|
|
if res := tx.Save(&slot.Card).Error; res != nil {
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
if res := tx.Preload("CardData.Groups").Save(&slot).Error; res != nil {
|
2022-01-25 05:22:33 +00:00
|
|
|
return res
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-03 06:13:46 +00:00
|
|
|
SetContactViewNotification(account, slot.Card)
|
2022-01-25 05:22:33 +00:00
|
|
|
SetStatus(account)
|
2022-02-03 06:13:46 +00:00
|
|
|
WriteResponse(w, getCardModel(&slot))
|
2022-01-25 05:22:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|