package api import ( "context" "net/http" "strconv" "strings" "unicode/utf8" "git.golem15.com/golem15/sm-journal-plugin/classes" "git.golem15.com/golem15/sm-journal-plugin/models" translate "git.golem15.com/golem15/sm-translate-plugin/classes" translatemodels "git.golem15.com/golem15/sm-translate-plugin/models" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/cabana" "git.golem15.com/golem15/summercms/modules/cooler" "git.golem15.com/golem15/summercms/modules/lagoon" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/towel" "git.golem15.com/golem15/summercms/modules/wire" "gorm.io/gorm" ) // ShowCategory is GET /_journal/api/v1/categories/{slug}. Resolves by default // slug, then translated slug in the request locale, then numeric id. func ShowCategory(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { db, err := gdb(app) if err != nil { writeAPIError(w, http.StatusInternalServerError, "Internal server error") return } dbCtx := db.WithContext(r.Context()) slug := strings.TrimSpace(r.PathValue("slug")) cat, err := findCategoryBySlugOrID(dbCtx, slug, requestLocale(r)) if err != nil || cat == nil { writeAPIError(w, http.StatusNotFound, errCategoryNotFound) return } h1ToH2 := classes.EffectiveH1ToH2(r.Context(), dbCtx, appConfig(app)) wire.WriteJSON(w, http.StatusOK, map[string]any{"data": serializeCategoryDetail(dbCtx, cat, h1ToH2)}) } } // UpdateCategory is PUT /_journal/api/v1/categories/{id}. Requires a backend // principal with golem15.journal.access_categories. Only submitted fields // change: name, slug, description, content (sanitized through the app's // EmbedRegistry, with H1→H2 conversion while the H1 setting is on, blank // stored as NULL), and optional translations. func UpdateCategory(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { r, pr, ok := requireBackendPrincipal(app, w, r) if !ok { return } if !requireAccessCategories(w, pr) { return } db, err := gdb(app) if err != nil { writeAPIError(w, http.StatusInternalServerError, "Internal server error") return } dbCtx := db.WithContext(r.Context()) cat, err := findCategoryByID(dbCtx, r.PathValue("id")) if err != nil || cat == nil { writeAPIError(w, http.StatusNotFound, errCategoryNotFound) return } body, err := readJSONObject(r) if err != nil { writeAPIError(w, http.StatusBadRequest, errValidationFailed) return } before := snapshotCategory(cat) verrs := applyCategoryUpdate(dbCtx, app, cat, body) if verrs != nil { writeValidation(w, verrs) return } h1Count := 0 err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error { if _, has := body["content"]; has && cat.Content != nil { if classes.EffectiveH1ToH2(ctx, tx, appConfig(app)) { converted, n := classes.ConvertH1(*cat.Content) if n > 0 { cat.Content = &converted h1Count = n } } } if err := tx.Save(cat).Error; err != nil { return err } if raw, has := body["translations"]; has { if err := syncCategoryTranslations(ctx, tx, cat, raw); err != nil { return err } } cabana.EmitRecordSaved(ctx, app, tx, categorySavedEvent(ctx, before, cat)) return nil }) if err != nil { writeAPIError(w, http.StatusInternalServerError, "Internal server error") return } cooler.PurgeSiteCacheAfterCommit(r.Context(), nil, cooler.SiteCacheFromApp(app), "category", cat.Slug) h1ToH2 := classes.EffectiveH1ToH2(r.Context(), dbCtx, appConfig(app)) payload := map[string]any{"data": serializeCategoryDetail(dbCtx, cat, h1ToH2)} if h1Count > 0 { msg := classes.EditorH1ConvertedCategory if app != nil { if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil { msg = tr.Choice(r.Context(), classes.EditorH1ConvertedCategory, h1Count, nil) } } payload["notices"] = []map[string]any{{"message": msg, "count": h1Count}} } wire.WriteJSON(w, http.StatusOK, payload) } } func findCategoryBySlugOrID(db *gorm.DB, slug, locale string) (*models.Category, error) { if slug == "" { return nil, gorm.ErrRecordNotFound } var cat models.Category if err := db.Where("slug = ?", slug).Take(&cat).Error; err == nil { return &cat, nil } if locale != "" { var ids []string err := db.Session(&gorm.Session{NewDB: true, Context: db.Statement.Context}). Table(translatemodels.Index{}.TableName()). Where("model_type = ? AND locale = ? AND item = ? AND value = ?", models.Category{}.MorphName(), locale, "slug", slug). Order("id ASC"). Pluck("model_id", &ids).Error if err == nil && len(ids) > 0 { var translated models.Category if err := db.Where("CAST(id AS TEXT) IN ?", ids).Order("id ASC").Take(&translated).Error; err == nil { return &translated, nil } } } if ctypeDigit(slug) { return findCategoryByID(db, slug) } return nil, gorm.ErrRecordNotFound } func findCategoryByID(db *gorm.DB, raw string) (*models.Category, error) { id, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64) if err != nil || id == 0 { return nil, gorm.ErrRecordNotFound } var cat models.Category if err := db.Where("id = ?", id).Take(&cat).Error; err != nil { return nil, err } return &cat, nil } func categorySlugTaken(db *gorm.DB, slug string, exceptID uint) bool { q := db.Model(&models.Category{}).Where("slug = ?", slug) if exceptID > 0 { q = q.Where("id <> ?", exceptID) } var n int64 _ = q.Count(&n).Error return n > 0 } func applyCategoryUpdate(db *gorm.DB, app *backpack.App, cat *models.Category, body map[string]any) map[string][]string { errs := map[string][]string{} if _, has := body["name"]; has { name := strings.TrimSpace(asString(body["name"])) if name == "" { errs["name"] = []string{"The name field is required."} } else if utf8.RuneCountInString(name) > 255 { errs["name"] = []string{"The name may not be greater than 255 characters."} } else { cat.Name = name } } if _, has := body["slug"]; has { slug := strings.TrimSpace(asString(body["slug"])) if slug == "" { errs["slug"] = []string{"The slug field is required."} } else if !slugPattern.MatchString(slug) { errs["slug"] = []string{"The slug format is invalid."} } else if categorySlugTaken(db, slug, cat.ID) { errs["slug"] = []string{"The slug has already been taken."} } else { cat.Slug = slug } } if _, has := body["description"]; has { if body["description"] == nil { cat.Description = nil } else { desc := strings.TrimSpace(asString(body["description"])) if desc == "" { cat.Description = nil } else { cat.Description = &desc } } } if _, has := body["content"]; has { if body["content"] == nil { cat.Content = nil } else { raw := asString(body["content"]) if strings.TrimSpace(raw) == "" { cat.Content = nil } else { clean := classes.EmbedRegistryFrom(app).SanitizeHTML(raw) if strings.TrimSpace(clean) == "" { cat.Content = nil } else { cat.Content = &clean } } } } if transErr := validateCategoryTranslations(body["translations"]); transErr != nil { errs["translations"] = []string{transErr.Error()} } if len(errs) > 0 { return errs } return nil } func validateCategoryTranslations(raw any) error { if raw == nil { return nil } m, ok := raw.(map[string]any) if !ok { return errInvalidCategoryTranslations } for _, v := range m { attrs, ok := v.(map[string]any) if !ok { continue } if slug := strings.TrimSpace(asString(attrs["slug"])); slug != "" && !slugPattern.MatchString(slug) { return errInvalidTranslationSlug } if name := asString(attrs["name"]); utf8.RuneCountInString(name) > 255 { return errInvalidTranslationName } } return nil } var ( errInvalidCategoryTranslations = categoryValidationError("The translations must be an object.") errInvalidTranslationSlug = categoryValidationError("The translations slug format is invalid.") errInvalidTranslationName = categoryValidationError("The translations name may not be greater than 255 characters.") ) type categoryValidationError string func (e categoryValidationError) Error() string { return string(e) } func syncCategoryTranslations(ctx context.Context, db *gorm.DB, cat *models.Category, raw any) error { m, ok := raw.(map[string]any) if !ok { return nil } for locale, v := range m { attrs, ok := v.(map[string]any) if !ok { continue } for _, field := range []string{"name", "slug", "description"} { if val, has := attrs[field]; has && val != nil { if err := translate.SetTranslated(ctx, db, cat, field, locale, val); err != nil { return err } } } } return nil } func serializeCategoryDetail(db *gorm.DB, c *models.Category, h1ToH2 bool) map[string]any { counts := publishedPostCounts(db, "golem15_journal_posts_categories", "category_id") var desc, content, parent, depth any if c.Description != nil { desc = *c.Description } if c.Content != nil { content = *c.Content } if c.ParentID != nil { parent = *c.ParentID } if c.NestDepth != nil { depth = *c.NestDepth } return map[string]any{ "id": c.ID, "name": c.Name, "slug": c.Slug, "description": desc, "content": content, "parent_id": parent, "nest_depth": depth, "post_count": counts[c.ID], "content_h1_to_h2": h1ToH2, "translations": categoryTranslationsOf(db, c), } } func categoryTranslationsOf(db *gorm.DB, c *models.Category) any { if db == nil || c == nil || c.ID == 0 { return []any{} } var locales []struct { Code string IsDefault bool } if err := db.Table("golem15_translate_locales"). Select("code, is_default"). Where("is_enabled = ?", true). Find(&locales).Error; err != nil { return []any{} } ctx := db.Statement.Context if ctx == nil { ctx = context.Background() } out := map[string]any{} for _, loc := range locales { if loc.IsDefault { continue } attrs := map[string]any{} for _, field := range []string{"name", "slug", "description"} { val, ok, err := translate.TranslatedExact(ctx, db, c, field, loc.Code) if err != nil || !ok || val == nil { continue } if strings.TrimSpace(asString(val)) == "" { continue } attrs[field] = val } if len(attrs) > 0 { out[loc.Code] = attrs } } if len(out) == 0 { return []any{} } return out } type categorySnapshot struct { name string slug string description any content any } func snapshotCategory(c *models.Category) categorySnapshot { return categorySnapshot{ name: c.Name, slug: c.Slug, description: derefValue(c.Description), content: derefValue(c.Content), } } func categorySavedEvent(ctx context.Context, before categorySnapshot, c *models.Category) pact.RecordSaved { changes := []pact.RecordChange{} if before.name != c.Name { changes = append(changes, pact.RecordChange{Attribute: "name", Old: before.name, New: c.Name}) } if before.slug != c.Slug { changes = append(changes, pact.RecordChange{Attribute: "slug", Old: before.slug, New: c.Slug}) } if nextDesc := derefValue(c.Description); !sameEventValue(before.description, nextDesc) { changes = append(changes, pact.RecordChange{Attribute: "description", Old: before.description, New: nextDesc}) } if nextContent := derefValue(c.Content); !sameEventValue(before.content, nextContent) { changes = append(changes, pact.RecordChange{Attribute: "content", Old: before.content, New: nextContent}) } locale, _ := towel.Locale(ctx) return pact.RecordSaved{ Model: c.MorphName(), ID: strconv.FormatUint(uint64(c.ID), 10), Locale: locale, Created: false, Changes: changes, } }