2018-06-10 19:49:40 +02:00
|
|
|
package models
|
|
|
|
|
2018-07-11 02:39:55 +02:00
|
|
|
// Create is the implementation to create a list item
|
|
|
|
func (i *ListItem) Create(doer *User, lID int64) (err error) {
|
|
|
|
i.ListID = lID
|
|
|
|
i.ID = 0
|
2018-06-10 19:49:40 +02:00
|
|
|
|
2018-07-11 02:39:55 +02:00
|
|
|
return createOrUpdateListItem(i, doer, lID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update updates a list item
|
|
|
|
func (i *ListItem) Update(ID int64, doer *User) (err error) {
|
|
|
|
i.ID = ID
|
2018-06-10 19:49:40 +02:00
|
|
|
|
2018-07-11 02:39:55 +02:00
|
|
|
// Get the full item
|
|
|
|
fullItem, err := GetListItemByID(ID)
|
2018-06-10 19:49:40 +02:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-06-13 12:18:55 +02:00
|
|
|
|
2018-07-11 02:39:55 +02:00
|
|
|
return createOrUpdateListItem(i, doer, fullItem.ListID)
|
2018-06-10 19:49:40 +02:00
|
|
|
}
|
2018-07-11 02:13:53 +02:00
|
|
|
|
2018-07-11 02:39:55 +02:00
|
|
|
// Helper function for creation or updating of new lists as both methods share most of their logic
|
|
|
|
func createOrUpdateListItem(i *ListItem, doer *User, lID int64) (err error) {
|
2018-07-11 02:13:53 +02:00
|
|
|
|
2018-07-11 11:44:17 +02:00
|
|
|
// Check rights
|
|
|
|
user, err := listItemPreCheck(i, doer, lID)
|
2018-07-11 02:13:53 +02:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if we have at least a text
|
|
|
|
if i.Text == "" {
|
|
|
|
return ErrListItemCannotBeEmpty{}
|
|
|
|
}
|
|
|
|
|
2018-07-11 02:39:55 +02:00
|
|
|
// Do the update
|
|
|
|
if i.ID != 0 {
|
|
|
|
_, err = x.ID(i.ID).Update(i)
|
|
|
|
} else {
|
|
|
|
i.CreatedByID = user.ID
|
|
|
|
i.CreatedBy = user
|
|
|
|
_, err = x.Insert(i)
|
2018-07-11 02:13:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
2018-07-11 11:44:17 +02:00
|
|
|
|
|
|
|
// This helper function checks if the user has the right to edit a list item.
|
|
|
|
// It is used in Create/Update/Delete.
|
|
|
|
func listItemPreCheck(i *ListItem, doer *User, lID int64) (user User, err error) {
|
|
|
|
// Check rights
|
|
|
|
user, _, err = GetUserByID(doer.ID)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the list to check if the user has the right to write to that list
|
|
|
|
list, err := GetListByID(lID) // TODO: Get the list with one query by item ID
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !list.CanWrite(&user) {
|
|
|
|
return user, ErrNeedToBeListWriter{ListID: i.ListID, UserID: user.ID}
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|