77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package useCases
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/audit"
|
|
"RenewCMS/internal/domain/author"
|
|
"context"
|
|
)
|
|
|
|
type ReassignMode int
|
|
|
|
const (
|
|
ReassignAbsent ReassignMode = iota
|
|
ReassignNone
|
|
ReassignToAuthor
|
|
ReassignMalformed
|
|
)
|
|
|
|
type Reassignment struct {
|
|
Mode ReassignMode
|
|
Destination uint32
|
|
}
|
|
|
|
type DeleteAuthorUseCase struct {
|
|
authors author.Repository
|
|
recorder audit.Recorder
|
|
}
|
|
|
|
func NewDeleteAuthorUseCase(authors author.Repository, recorder audit.Recorder) *DeleteAuthorUseCase {
|
|
return &DeleteAuthorUseCase{authors: authors, recorder: recorder}
|
|
}
|
|
|
|
func (u *DeleteAuthorUseCase) Delete(ctx context.Context, id uint32, reassignment Reassignment) error {
|
|
target, err := u.authors.Get(id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
event := audit.NewEvent(audit.ActionAuthorDelete, audit.CategoryAuthors)
|
|
event.Target = authorTarget(target)
|
|
if err := u.delete(target, reassignment); err != nil {
|
|
recordFailure(ctx, u.recorder, event, err)
|
|
return err
|
|
}
|
|
u.recorder.Record(ctx, event)
|
|
return nil
|
|
}
|
|
|
|
func (u *DeleteAuthorUseCase) delete(target author.Author, reassignment Reassignment) error {
|
|
if reassignment.Mode == ReassignNone {
|
|
return u.authors.DeleteUncrediting(target.ID)
|
|
}
|
|
if target.ArticleCount == 0 {
|
|
return u.authors.DeleteMovingCredits(target.ID, nil)
|
|
}
|
|
destination, err := u.destination(target, reassignment)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return u.authors.DeleteMovingCredits(target.ID, &destination)
|
|
}
|
|
|
|
func (u *DeleteAuthorUseCase) destination(target author.Author, reassignment Reassignment) (uint32, error) {
|
|
switch reassignment.Mode {
|
|
case ReassignAbsent:
|
|
return 0, author.ErrAuthorHasArticles
|
|
case ReassignMalformed:
|
|
return 0, author.ErrInvalidReassign
|
|
}
|
|
if reassignment.Destination == 0 || reassignment.Destination == target.ID {
|
|
return 0, author.ErrInvalidReassign
|
|
}
|
|
if _, err := u.authors.Get(reassignment.Destination); err != nil {
|
|
return 0, err
|
|
}
|
|
return reassignment.Destination, nil
|
|
}
|