package useCases import ( "RenewCMS/internal/domain/article" "RenewCMS/internal/domain/audit" "RenewCMS/internal/domain/author" "RenewCMS/internal/domain/builtintype" "RenewCMS/internal/domain/image" "RenewCMS/internal/domain/language" "RenewCMS/internal/domain/localization" "RenewCMS/internal/domain/role" "RenewCMS/internal/domain/site" "RenewCMS/internal/domain/transaction" "context" "slices" "strconv" "strings" ) type UpdateArticleUseCase struct { articleRepository article.Repository bodyRenderer article.BodyRenderer recorder audit.Recorder sites site.Repository authors author.Repository images image.Repository localization localization.Repository storyMover StoryMover } type UpdateArticleCommand struct { Title *string IfRevision *uint32 Body *string SiteID *uint32 AuthorIDs *[]uint32 Slug *string Excerpt *string SEOTitle *string SEODescription *string CoverImageID article.Nullable[uint32] CoverImageAlt *string SocialTitle *string SocialDescription *string SocialImageID article.Nullable[uint32] CanonicalURL *string Noindex *bool SEODismissed *[]string Format article.BodyFormat } func NewUpdateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer, recorder audit.Recorder, sites site.Repository, authors author.Repository, images image.Repository, localizationRepository localization.Repository, storyMover StoryMover) *UpdateArticleUseCase { return &UpdateArticleUseCase{articleRepository: articleRepository, bodyRenderer: bodyRenderer, recorder: recorder, sites: sites, authors: authors, images: images, localization: localizationRepository, storyMover: storyMover} } func (g *UpdateArticleUseCase) UpdateBody(ctx context.Context, id uint32, caller ContentCaller, body string, format article.BodyFormat) (article.Article, error) { return g.Update(ctx, id, caller, UpdateArticleCommand{Body: &body, Format: format}) } func (g *UpdateArticleUseCase) Update(ctx context.Context, id uint32, caller ContentCaller, command UpdateArticleCommand) (article.Article, error) { if err := caller.requireHolding(role.KeyContentUpdate, builtintype.KeyArticle); err != nil { return article.Article{}, err } before, err := g.articleRepository.Get(id) if err != nil { return article.Article{}, err } if err := caller.authorize(role.KeyContentUpdate, builtintype.KeyArticle, before.CreatedBy); err != nil { return article.Article{}, err } if !caller.seesArticle(before) { return article.Article{}, article.ErrArticleNotFound } if command.IfRevision != nil && before.EditRevision != *command.IfRevision { err := &article.RevisionConflictError{Current: before.EditRevision} g.recordFailure(ctx, audit.ActionArticleEdit, before, err) return article.Article{}, err } if command.Title != nil { if err := article.ValidateTitle(*command.Title); err != nil { g.recordFailure(ctx, audit.ActionArticleEdit, before, err) return article.Article{}, err } } destination, err := g.destinationSite(command) if err != nil { return article.Article{}, err } movesWholeStory, err := g.checkSingleVersionMove(before, caller, command) if err != nil { g.recordFailure(ctx, audit.ActionArticleEdit, before, err) return article.Article{}, err } if err := g.ensureAuthorsExist(command.AuthorIDs); err != nil { return article.Article{}, err } if err := g.validateSEO(command); err != nil { return article.Article{}, err } update := command.toUpdate() slug, err := g.resolveSlug(before, command) if err != nil { g.recordFailure(ctx, audit.ActionArticleEdit, before, err) return article.Article{}, err } update.Slug = slug if movesWholeStory { return g.updateWithStory(ctx, id, caller, before, command, destination, update, slug) } updated, err := g.articleRepository.Update(id, update) return g.finishEdit(ctx, before, command, slug, destination, updated, err) } func (g *UpdateArticleUseCase) updateWithStory(ctx context.Context, id uint32, caller ContentCaller, before article.Article, command UpdateArticleCommand, destination *site.Site, update article.Update, slug *string) (article.Article, error) { var updated article.Article var writeErr error move := MoveStoryCommand{StoryID: before.StoryID, SiteKey: destination.Key, Caller: caller, SkipArticleID: id} _, err := g.storyMover.MoveStoryThen(ctx, move, func(tx transaction.Repositories) error { updated, writeErr = tx.Articles.Update(id, update) return writeErr }) if err != nil && writeErr == nil { return article.Article{}, err } return g.finishEdit(ctx, before, command, slug, destination, updated, err) } func (g *UpdateArticleUseCase) finishEdit(ctx context.Context, before article.Article, command UpdateArticleCommand, slug *string, destination *site.Site, updated article.Article, err error) (article.Article, error) { if isSlugTakenError(err) { err = g.raceConflict(before, command, slug) } if err != nil { g.recordFailure(ctx, audit.ActionArticleEdit, before, err) return article.Article{}, err } g.recordEdit(ctx, before, updated, destination) return renderArticle(g.bodyRenderer, updated, command.Format) } func (c UpdateArticleCommand) toUpdate() article.Update { update := article.Update{ Title: c.Title, IfRevision: c.IfRevision, Body: c.Body, SiteID: c.SiteID, AuthorIDs: c.AuthorIDs, Excerpt: c.Excerpt, SEOTitle: c.SEOTitle, SEODescription: c.SEODescription, CoverImageID: c.CoverImageID, CoverImageAlt: c.CoverImageAlt, SocialTitle: c.SocialTitle, SocialDescription: c.SocialDescription, SocialImageID: c.SocialImageID, CanonicalURL: c.CanonicalURL, Noindex: c.Noindex, } if c.SEODismissed != nil { normalized := article.NormalizeDismissed(*c.SEODismissed) update.SEODismissed = &normalized } return update } func (g *UpdateArticleUseCase) validateSEO(command UpdateArticleCommand) error { if command.Slug != nil && *command.Slug != "" && !article.IsValidSlug(*command.Slug) { return article.ErrInvalidSlug } if command.CanonicalURL != nil { if err := article.ValidateCanonicalURL(*command.CanonicalURL); err != nil { return err } } if command.CoverImageID.Set { if err := ensureImageExists(g.images, command.CoverImageID.Value); err != nil { return err } } if command.SocialImageID.Set { return ensureImageExists(g.images, command.SocialImageID.Value) } return nil } func targetSiteID(before article.Article, command UpdateArticleCommand) uint32 { if command.SiteID != nil { return *command.SiteID } return before.SiteID } func requestedSlug(before article.Article, command UpdateArticleCommand) string { if command.Slug == nil { return before.Slug } if *command.Slug == "" { return article.GenerateSlug(before.Title) } return *command.Slug } func (g *UpdateArticleUseCase) resolveSlug(before article.Article, command UpdateArticleCommand) (*string, error) { target := targetSiteID(before, command) slug := requestedSlug(before, command) if slug == "" || (slug == before.Slug && target == before.SiteID) { return nil, nil } taken, err := g.articleRepository.SlugTaken(target, before.Lang, slug, before.ID) if err != nil { return nil, err } if taken { return nil, slugConflict(g.articleRepository, target, before.Lang, slug, before.ID) } if slug == before.Slug { return nil, nil } return &slug, nil } func (g *UpdateArticleUseCase) raceConflict(before article.Article, command UpdateArticleCommand, chosen *string) error { slug := requestedSlug(before, command) if chosen != nil { slug = *chosen } return slugConflict(g.articleRepository, targetSiteID(before, command), before.Lang, slug, before.ID) } func (g *UpdateArticleUseCase) destinationSite(command UpdateArticleCommand) (*site.Site, error) { if command.SiteID == nil { return nil, nil } destination, err := g.sites.Get(*command.SiteID) if err != nil { return nil, err } return &destination, nil } func (g *UpdateArticleUseCase) checkSingleVersionMove(before article.Article, caller ContentCaller, command UpdateArticleCommand) (bool, error) { if command.SiteID == nil || *command.SiteID == before.SiteID { return false, nil } versions, err := g.articleRepository.ListByStory(before.StoryID) if err != nil { return false, err } if len(caller.readableVersions(versions)) > 1 { return false, article.ErrStoryMoveRequired } if err := requireUpdateOnAll(caller, versions); err != nil { return false, err } if len(versions) > 1 { return true, nil } rows, err := g.localization.Rows(*command.SiteID) if err != nil { return false, err } if missing := localization.MissingTags(rows, []string{before.Lang}); len(missing) > 0 { return false, &article.LanguageNotEnabledError{Missing: missing} } return false, nil } func (g *UpdateArticleUseCase) checkPublishable(before article.Article, isOnline bool) error { if !isOnline || before.IsOnline || before.Lang == language.Unassigned { return nil } rows, err := g.localization.Rows(before.SiteID) if err != nil { return err } if !localization.EnabledTag(rows, before.Lang) { return article.ErrLanguageDisabled } return nil } func (g *UpdateArticleUseCase) ensureAuthorsExist(ids *[]uint32) error { if ids == nil { return nil } for _, id := range *ids { if _, err := g.authors.Get(id); err != nil { return err } } return nil } func authorsChange(before article.Article, after article.Article) (audit.Change, bool) { beforeIDs := author.BylineIDs(before.Authors) afterIDs := author.BylineIDs(after.Authors) if slices.Equal(beforeIDs, afterIDs) { return audit.Change{}, false } return audit.TextChange(audit.FieldAuthors, bylineNames(before.Authors), bylineNames(after.Authors)), true } func bylineNames(bylines []author.Byline) string { names := make([]string, 0, len(bylines)) for _, byline := range bylines { names = append(names, byline.Name) } return strings.Join(names, authorChangeSeparator) } func (g *UpdateArticleUseCase) recordEdit(ctx context.Context, before article.Article, after article.Article, destination *site.Site) { changes := audit.ArticleChanges(before, after) changes = append(changes, audit.SEOChanges(before, after)...) changes = append(changes, g.imageChanges(before, after)...) if destination != nil && before.SiteID != after.SiteID { changes = append(changes, audit.TextChange(audit.FieldSite, g.siteName(before.SiteID), destination.Name)) } if change, changed := authorsChange(before, after); changed { changes = append(changes, change) } if len(changes) == 0 { return } event := articleEvent(audit.ActionArticleEdit, after) event.Changes = changes g.recorder.Record(ctx, event) } func (g *UpdateArticleUseCase) imageChanges(before article.Article, after article.Article) []audit.Change { changes := []audit.Change{} if !sameImage(before.CoverImageID, after.CoverImageID) { changes = append(changes, audit.TextChange(audit.FieldCoverImage, imageLabel(g.images, before.CoverImageID), imageLabel(g.images, after.CoverImageID))) } if !sameImage(before.SocialImageID, after.SocialImageID) { changes = append(changes, audit.TextChange(audit.FieldArticleSocialImage, imageLabel(g.images, before.SocialImageID), imageLabel(g.images, after.SocialImageID))) } return changes } func (g *UpdateArticleUseCase) siteName(id uint32) string { found, err := g.sites.Get(id) if err != nil { return strconv.FormatUint(uint64(id), 10) } return found.Name } func (g *UpdateArticleUseCase) UpdateIsOnline(ctx context.Context, id uint32, caller ContentCaller, isOnline bool, format article.BodyFormat) (article.Article, error) { if err := caller.requireHolding(role.KeyContentPublish, builtintype.KeyArticle); err != nil { return article.Article{}, err } before, err := g.articleRepository.Get(id) if err != nil { return article.Article{}, err } if err := caller.authorize(role.KeyContentPublish, builtintype.KeyArticle, before.CreatedBy); err != nil { return article.Article{}, err } if err := g.checkPublishable(before, isOnline); err != nil { g.recordFailure(ctx, publishAction(isOnline), before, err) return article.Article{}, err } updated, err := g.articleRepository.UpdateIsOnline(id, isOnline) if err != nil { g.recordFailure(ctx, publishAction(isOnline), before, err) return article.Article{}, err } g.recordChange(ctx, publishAction(isOnline), before, updated) return renderArticle(g.bodyRenderer, updated, format) } func publishAction(isOnline bool) string { if isOnline { return audit.ActionArticlePublish } return audit.ActionArticleUnpublish } func (g *UpdateArticleUseCase) recordChange(ctx context.Context, action string, before article.Article, after article.Article) { changes := audit.ArticleChanges(before, after) if len(changes) == 0 { return } event := articleEvent(action, after) event.Changes = changes g.recorder.Record(ctx, event) } func (g *UpdateArticleUseCase) recordFailure(ctx context.Context, action string, before article.Article, cause error) { recordFailure(ctx, g.recorder, articleEvent(action, before), cause) }