daddy/internal/graph/dsf_handler.go

121 lines
2.8 KiB
Go

package graph
import (
"context"
"reflect"
"forge.cadoles.com/Cadoles/daddy/internal/orm"
"gitlab.com/wpetit/goweb/middleware/container"
"forge.cadoles.com/Cadoles/daddy/internal/model"
errs "github.com/pkg/errors"
)
func handleCreateDecisionSupportFile(ctx context.Context, changes *model.DecisionSupportFileChanges) (*model.DecisionSupportFile, error) {
user, db, err := getSessionUser(ctx)
if err != nil {
return nil, errs.WithStack(err)
}
authorized, err := isAuthorized(ctx, &model.DecisionSupportFile{}, model.ActionCreate)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
repo := model.NewDSFRepository(db)
dsf, err := repo.Create(ctx, changes)
if err != nil {
return nil, errs.WithStack(err)
}
eventRepo := model.NewEventRepository(db)
if _, err := eventRepo.Add(ctx, user, model.EventTypeCreated, dsf); err != nil {
return nil, errs.WithStack(err)
}
return dsf, nil
}
func handleUpdateDecisionSupportFile(ctx context.Context, id string, changes *model.DecisionSupportFileChanges) (*model.DecisionSupportFile, error) {
user, db, err := getSessionUser(ctx)
if err != nil {
return nil, errs.WithStack(err)
}
repo := model.NewDSFRepository(db)
prevDsf, err := repo.Find(ctx, id)
if err != nil {
return nil, errs.WithStack(err)
}
authorized, err := isAuthorized(ctx, prevDsf, model.ActionUpdate)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
dsf, err := repo.Update(ctx, id, changes)
if err != nil {
return nil, errs.WithStack(err)
}
eventRepo := model.NewEventRepository(db)
if changes != nil && changes.Status != nil && prevDsf.Status != *changes.Status {
if _, err := eventRepo.Add(ctx, user, model.EventTypeStatusChanged, dsf); err != nil {
return nil, errs.WithStack(err)
}
}
if changes != nil && changes.Title != nil && prevDsf.Title != *changes.Title {
if _, err := eventRepo.Add(ctx, user, model.EventTypeTitleChanged, dsf); err != nil {
return nil, errs.WithStack(err)
}
}
if changes != nil && !reflect.DeepEqual(prevDsf.Sections, dsf.Sections) {
if _, err := eventRepo.Add(ctx, user, model.EventTypeUpdated, dsf); err != nil {
return nil, errs.WithStack(err)
}
}
return dsf, nil
}
func handleDecisionSupportFiles(ctx context.Context, filter *model.DecisionSupportFileFilter) ([]*model.DecisionSupportFile, error) {
ctn := container.Must(ctx)
db := orm.Must(ctn).DB()
repo := model.NewDSFRepository(db)
found, err := repo.Search(ctx, filter)
if err != nil {
return nil, errs.WithStack(err)
}
dsfs := make([]*model.DecisionSupportFile, 0)
for _, d := range found {
authorized, err := isAuthorized(ctx, d, model.ActionRead)
if err != nil {
return nil, errs.WithStack(err)
}
if authorized {
dsfs = append(dsfs, d)
}
}
return dsfs, nil
}