Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
813 lines
26 KiB
Go
813 lines
26 KiB
Go
package api
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"net/http"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/go-chi/chi/v5"
|
||
"github.com/jackc/pgx/v5"
|
||
|
||
"github.com/yourorg/article-platform/internal/domain"
|
||
"github.com/yourorg/article-platform/internal/platform/cache"
|
||
"github.com/yourorg/article-platform/internal/platform/httpx"
|
||
"github.com/yourorg/article-platform/internal/platform/idgen"
|
||
"github.com/yourorg/article-platform/internal/platform/middleware"
|
||
"github.com/yourorg/article-platform/internal/platform/rbac"
|
||
"github.com/yourorg/article-platform/internal/repo"
|
||
)
|
||
|
||
// ══════════════════════ 用户侧:回收站 ══════════════════════
|
||
|
||
// listTrashArticles 当前用户回收站列表(软删除文章)
|
||
func (d *Deps) listTrashArticles(w http.ResponseWriter, r *http.Request) {
|
||
limit, offset := pageParams(r)
|
||
items, total, err := d.Articles.ListPage(r.Context(), d.Pool, repo.PageParams{
|
||
OwnerID: middleware.UserID(r.Context()),
|
||
OnlyDeleted: true,
|
||
Limit: limit,
|
||
Offset: offset,
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total})
|
||
}
|
||
|
||
// restoreArticleByID 恢复软删除文章。路径参数兼容 UUID 与 mask_id。
|
||
func (d *Deps) restoreArticleByID(w http.ResponseWriter, r *http.Request, rawID string, requireOwner bool) {
|
||
var ownerID string
|
||
err := d.Pool.QueryRow(r.Context(),
|
||
`SELECT owner_id FROM articles WHERE (id::text=$1 OR mask_id=$1) AND deleted_at IS NOT NULL`,
|
||
strings.TrimSpace(rawID)).Scan(&ownerID)
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("回收站中不存在该文章"))
|
||
return
|
||
}
|
||
if requireOwner && ownerID != middleware.UserID(r.Context()) &&
|
||
!middleware.Role(r.Context()).AtLeast(rbac.RoleOperator) {
|
||
httpx.WriteError(w, httpx.ErrForbidden)
|
||
return
|
||
}
|
||
if err := d.Articles.Restore(r.Context(), d.Pool, strings.TrimSpace(rawID)); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
d.invalidateFeeds(r, nil)
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
func (d *Deps) userRestoreArticle(w http.ResponseWriter, r *http.Request) {
|
||
d.restoreArticleByID(w, r, chi.URLParam(r, "maskID"), true)
|
||
}
|
||
|
||
func (d *Deps) adminRecycleRestore(w http.ResponseWriter, r *http.Request) {
|
||
d.restoreArticleByID(w, r, chi.URLParam(r, "articleID"), false)
|
||
}
|
||
|
||
// hardDeleteByID 物理删除文章(级联删区块/评论/互动)。路径参数兼容 UUID 与 mask_id。
|
||
func (d *Deps) hardDeleteByID(w http.ResponseWriter, r *http.Request, rawID string, requireOwner bool) {
|
||
rawID = strings.TrimSpace(rawID)
|
||
var id, ownerID, maskID string
|
||
err := d.Pool.QueryRow(r.Context(),
|
||
`SELECT id, owner_id, mask_id FROM articles WHERE (id::text=$1 OR mask_id=$1) AND deleted_at IS NOT NULL`,
|
||
rawID).Scan(&id, &ownerID, &maskID)
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("回收站中不存在该文章"))
|
||
return
|
||
}
|
||
if requireOwner && ownerID != middleware.UserID(r.Context()) &&
|
||
!middleware.Role(r.Context()).AtLeast(rbac.RoleOperator) {
|
||
httpx.WriteError(w, httpx.ErrForbidden)
|
||
return
|
||
}
|
||
if err := d.Articles.HardDelete(r.Context(), d.Pool, id); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(maskID))
|
||
d.invalidateFeeds(r, nil)
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
func (d *Deps) userPermanentlyDelete(w http.ResponseWriter, r *http.Request) {
|
||
d.hardDeleteByID(w, r, chi.URLParam(r, "maskID"), true)
|
||
}
|
||
|
||
func (d *Deps) adminRecycleDelete(w http.ResponseWriter, r *http.Request) {
|
||
d.hardDeleteByID(w, r, chi.URLParam(r, "articleID"), false)
|
||
}
|
||
|
||
// adminRecycleList 管理端回收站列表(全部用户)
|
||
func (d *Deps) adminRecycleList(w http.ResponseWriter, r *http.Request) {
|
||
limit, offset := pageParams(r)
|
||
items, total, err := d.Articles.ListPage(r.Context(), d.Pool, repo.PageParams{
|
||
OnlyDeleted: true,
|
||
Keyword: r.URL.Query().Get("keyword"),
|
||
Limit: limit,
|
||
Offset: offset,
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total})
|
||
}
|
||
|
||
// ══════════════════════ 用户侧:话题文章 ══════════════════════
|
||
|
||
// topicArticles 话题下已发布文章列表
|
||
func (d *Deps) topicArticles(w http.ResponseWriter, r *http.Request) {
|
||
limit, offset := pageParams(r)
|
||
items, total, err := d.Articles.ListByTopic(r.Context(), d.Pool, chi.URLParam(r, "topicID"), limit, offset)
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
for i := range items {
|
||
if items[i].CoverImgURL != nil {
|
||
items[i].CoverURL = items[i].CoverImgURL
|
||
}
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total})
|
||
}
|
||
|
||
// ══════════════════════ 用户侧:套用模板 ══════════════════════
|
||
|
||
// applyTemplate 用模板生成一篇新草稿,返回新文章对象
|
||
func (d *Deps) applyTemplate(w http.ResponseWriter, r *http.Request) {
|
||
tpl, err := d.Templates.GetByID(r.Context(), d.Pool, chi.URLParam(r, "templateID"))
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("模板不存在"))
|
||
return
|
||
}
|
||
|
||
var req struct {
|
||
Title string `json:"title"`
|
||
Abstract string `json:"abstract"`
|
||
CoverImgURL string `json:"cover_img_url"`
|
||
}
|
||
_ = httpx.Decode(r, &req)
|
||
|
||
title := strings.TrimSpace(req.Title)
|
||
if title == "" {
|
||
title = tpl.Title
|
||
}
|
||
if len([]rune(title)) > 200 {
|
||
title = string([]rune(title)[:200])
|
||
}
|
||
|
||
// 解析模板区块:兼容 [{kind, payload}] 与直接存整个区块对象两种写法。
|
||
// pgx 把 jsonb 扫进 any 可能得到 []byte / string / []any / map[string]any,
|
||
// 统一先序列化回 JSON 字节再解析。
|
||
var rawSecs []json.RawMessage
|
||
switch sv := tpl.SectionsJSON.(type) {
|
||
case nil:
|
||
case []byte:
|
||
_ = json.Unmarshal(sv, &rawSecs)
|
||
case string:
|
||
_ = json.Unmarshal([]byte(sv), &rawSecs)
|
||
case []any, map[string]any:
|
||
if b, err := json.Marshal(sv); err == nil {
|
||
_ = json.Unmarshal(b, &rawSecs)
|
||
}
|
||
default:
|
||
if b, err := json.Marshal(sv); err == nil {
|
||
_ = json.Unmarshal(b, &rawSecs)
|
||
}
|
||
}
|
||
secs := make([]domain.Section, 0, len(rawSecs))
|
||
for i, raw := range rawSecs {
|
||
var head struct {
|
||
Kind string `json:"kind"`
|
||
Payload json.RawMessage `json:"payload"`
|
||
}
|
||
if err := json.Unmarshal(raw, &head); err != nil || head.Kind == "" {
|
||
continue
|
||
}
|
||
payload := head.Payload
|
||
if len(payload) == 0 || string(payload) == "null" {
|
||
var whole map[string]any
|
||
if json.Unmarshal(raw, &whole) == nil {
|
||
delete(whole, "kind")
|
||
delete(whole, "id")
|
||
delete(whole, "order_index")
|
||
if b, err := json.Marshal(whole); err == nil {
|
||
payload = b
|
||
}
|
||
}
|
||
}
|
||
if len(payload) == 0 {
|
||
payload = json.RawMessage("{}")
|
||
}
|
||
secs = append(secs, domain.Section{
|
||
ID: idgen.NewUUIDv7(),
|
||
Kind: domain.Kind(head.Kind),
|
||
OrderIndex: i,
|
||
Payload: payload,
|
||
})
|
||
}
|
||
|
||
uid := middleware.UserID(r.Context())
|
||
now := time.Now().UTC()
|
||
a := &domain.Article{
|
||
ID: idgen.NewUUIDv7(),
|
||
MaskID: idgen.MaskID("art"),
|
||
Title: title,
|
||
Status: domain.StatusDraft,
|
||
ReviewStatus: domain.ReviewPending,
|
||
OwnerID: uid,
|
||
Privacy: domain.PrivacyPublic,
|
||
EnableComment: true,
|
||
CreatedAt: now,
|
||
UpdatedAt: now,
|
||
VisualConfig: json.RawMessage("{}"),
|
||
InteractionConfig: json.RawMessage("{}"),
|
||
}
|
||
if tpl.CoverURL != nil && req.CoverImgURL == "" {
|
||
a.CoverImgURL = tpl.CoverURL
|
||
a.CoverURL = tpl.CoverURL
|
||
} else if req.CoverImgURL != "" {
|
||
a.CoverImgURL = &req.CoverImgURL
|
||
a.CoverURL = &req.CoverImgURL
|
||
}
|
||
if req.Abstract != "" {
|
||
a.Abstract = &req.Abstract
|
||
} else if tpl.Description != nil {
|
||
a.Abstract = tpl.Description
|
||
}
|
||
|
||
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
|
||
if err := d.Articles.Insert(r.Context(), tx, a); err != nil {
|
||
return err
|
||
}
|
||
for i := range secs {
|
||
secs[i].ArticleID = a.ID
|
||
if err := d.Articles.UpsertSection(r.Context(), tx, &secs[i]); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
return nil
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
a.Sections = secs
|
||
httpx.WriteJSON(w, http.StatusCreated, a)
|
||
}
|
||
|
||
// ══════════════════════ 管理端:内容审核 ══════════════════════
|
||
|
||
// adminAuditArticles 审核列表(page 分页 + review_status 筛选)
|
||
func (d *Deps) adminAuditArticles(w http.ResponseWriter, r *http.Request) {
|
||
limit, offset := pageParams(r)
|
||
items, total, err := d.Articles.ListPage(r.Context(), d.Pool, repo.PageParams{
|
||
ReviewStatus: r.URL.Query().Get("status"),
|
||
Status: r.URL.Query().Get("article_status"),
|
||
Limit: limit,
|
||
Offset: offset,
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total})
|
||
}
|
||
|
||
// reviewArticleByID 执行单篇审核。approve=true 发布,false 驳回回草稿。
|
||
func (d *Deps) reviewArticleByID(w http.ResponseWriter, r *http.Request, idOrMask string, approve bool, note string) {
|
||
a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, idOrMask)
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("文章不存在"))
|
||
return
|
||
}
|
||
|
||
uid := middleware.UserID(r.Context())
|
||
now := time.Now().UTC()
|
||
if approve {
|
||
a.Status = domain.StatusPublished
|
||
a.ReviewStatus = domain.ReviewApproved
|
||
if a.PublishedAt == nil {
|
||
a.PublishedAt = &now
|
||
}
|
||
} else {
|
||
a.Status = domain.StatusDraft
|
||
a.ReviewStatus = domain.ReviewRejected
|
||
}
|
||
a.ReviewNote = ¬e
|
||
a.ReviewedBy = &uid
|
||
a.ReviewedAt = &now
|
||
|
||
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
|
||
if err := d.Articles.Update(r.Context(), tx, a); err != nil {
|
||
return err
|
||
}
|
||
if err := d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "upsert"); err != nil {
|
||
return err
|
||
}
|
||
return refreshTopicArticleCount(r.Context(), tx, a.TopicID)
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
|
||
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
|
||
d.invalidateFeeds(r, a.CategoryID)
|
||
|
||
verdict := "已通过审核"
|
||
if !approve {
|
||
verdict = "已驳回"
|
||
}
|
||
d.notify(r, a.OwnerID, uid, "review", "article", a.ID, "审核结果", verdict+":"+note)
|
||
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{
|
||
"mask_id": a.MaskID, "status": a.Status, "review_status": a.ReviewStatus,
|
||
})
|
||
}
|
||
|
||
func (d *Deps) adminAuditApprove(w http.ResponseWriter, r *http.Request) {
|
||
d.reviewArticleByID(w, r, chi.URLParam(r, "articleID"), true, "")
|
||
}
|
||
|
||
func (d *Deps) adminAuditReject(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Reason string `json:"reason"`
|
||
}
|
||
_ = httpx.Decode(r, &req)
|
||
d.reviewArticleByID(w, r, chi.URLParam(r, "articleID"), false, strings.TrimSpace(req.Reason))
|
||
}
|
||
|
||
func (d *Deps) adminAuditBatch(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
ArticleIDs []string `json:"article_ids"`
|
||
Action string `json:"action"`
|
||
}
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
if len(req.ArticleIDs) == 0 {
|
||
httpx.WriteError(w, httpx.InvalidParam("article_ids 不能为空"))
|
||
return
|
||
}
|
||
if req.Action != "approve" && req.Action != "reject" {
|
||
httpx.WriteError(w, httpx.InvalidParam("action 只能是 approve 或 reject"))
|
||
return
|
||
}
|
||
|
||
var ok, fail int
|
||
for _, id := range req.ArticleIDs {
|
||
a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, strings.TrimSpace(id))
|
||
if err != nil {
|
||
fail++
|
||
continue
|
||
}
|
||
uid := middleware.UserID(r.Context())
|
||
now := time.Now().UTC()
|
||
if req.Action == "approve" {
|
||
a.Status = domain.StatusPublished
|
||
a.ReviewStatus = domain.ReviewApproved
|
||
if a.PublishedAt == nil {
|
||
a.PublishedAt = &now
|
||
}
|
||
} else {
|
||
a.Status = domain.StatusDraft
|
||
a.ReviewStatus = domain.ReviewRejected
|
||
}
|
||
a.ReviewedBy = &uid
|
||
a.ReviewedAt = &now
|
||
|
||
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
|
||
if err := d.Articles.Update(r.Context(), tx, a); err != nil {
|
||
return err
|
||
}
|
||
if err := d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "upsert"); err != nil {
|
||
return err
|
||
}
|
||
return refreshTopicArticleCount(r.Context(), tx, a.TopicID)
|
||
})
|
||
if err != nil {
|
||
fail++
|
||
continue
|
||
}
|
||
ok++
|
||
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
|
||
d.invalidateFeeds(r, a.CategoryID)
|
||
d.notify(r, a.OwnerID, uid, "review", "article", a.ID, "审核结果",
|
||
map[bool]string{true: "已通过审核", false: "已驳回"}[req.Action == "approve"])
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "processed": ok, "failed": fail})
|
||
}
|
||
|
||
// refreshTopicArticleCount 文章发布/下架后重算话题的文章数
|
||
func refreshTopicArticleCount(ctx context.Context, q repo.Querier, topicID *string) error {
|
||
if topicID == nil || *topicID == "" {
|
||
return nil
|
||
}
|
||
_, err := q.Exec(ctx, `UPDATE topics SET article_count = (
|
||
SELECT count(*) FROM articles
|
||
WHERE topic_id = $1 AND status='published' AND deleted_at IS NULL), updated_at=now()
|
||
WHERE id = $1`, *topicID)
|
||
return err
|
||
}
|
||
|
||
// ══════════════════════ 管理端:文章管理 ══════════════════════
|
||
|
||
// adminArticlesPage 管理端文章分页列表(page/size + total)
|
||
func (d *Deps) adminArticlesPage(w http.ResponseWriter, r *http.Request) {
|
||
limit, offset := pageParams(r)
|
||
items, total, err := d.Articles.ListPage(r.Context(), d.Pool, repo.PageParams{
|
||
Status: r.URL.Query().Get("status"),
|
||
ReviewStatus: r.URL.Query().Get("review_status"),
|
||
CategoryID: r.URL.Query().Get("category_id"),
|
||
Keyword: r.URL.Query().Get("keyword"),
|
||
Limit: limit,
|
||
Offset: offset,
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total})
|
||
}
|
||
|
||
// adminOfflineArticle 下架文章
|
||
func (d *Deps) adminOfflineArticle(w http.ResponseWriter, r *http.Request) {
|
||
a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, chi.URLParam(r, "maskID"))
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("文章不存在"))
|
||
return
|
||
}
|
||
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
|
||
if err := d.Articles.UpdateStatus(r.Context(), tx, a.ID, domain.StatusOffline, domain.ReviewApproved); err != nil {
|
||
return err
|
||
}
|
||
if err := d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "delete"); err != nil {
|
||
return err
|
||
}
|
||
return refreshTopicArticleCount(r.Context(), tx, a.TopicID)
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
|
||
d.invalidateFeeds(r, a.CategoryID)
|
||
d.notify(r, a.OwnerID, middleware.UserID(r.Context()), "review", "article", a.ID, "文章已被下架", "文章因违规或运营需要已被下架")
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "status": domain.StatusOffline})
|
||
}
|
||
|
||
// adminDeleteArticle 管理端删除(软删除,进入回收站)
|
||
func (d *Deps) adminDeleteArticle(w http.ResponseWriter, r *http.Request) {
|
||
a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, chi.URLParam(r, "maskID"))
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("文章不存在"))
|
||
return
|
||
}
|
||
if err := d.Articles.SoftDelete(r.Context(), d.Pool, a.ID); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
|
||
d.invalidateFeeds(r, a.CategoryID)
|
||
_ = refreshTopicArticleCount(r.Context(), d.Pool, a.TopicID)
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
// ══════════════════════ 管理端:评论管理 ══════════════════════
|
||
|
||
func (d *Deps) adminHideComment(w http.ResponseWriter, r *http.Request) {
|
||
if err := d.Comments.SetStatus(r.Context(), d.Pool, chi.URLParam(r, "commentID"), "hidden"); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
func (d *Deps) adminDeleteComment(w http.ResponseWriter, r *http.Request) {
|
||
c, err := d.Comments.GetByID(r.Context(), d.Pool, chi.URLParam(r, "commentID"))
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("评论不存在"))
|
||
return
|
||
}
|
||
if err := d.Comments.SetStatus(r.Context(), d.Pool, c.ID, "deleted"); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
d.Cache.IncrCounter(r.Context(), c.ArticleID, "comment", -1)
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
// ══════════════════════ 管理端:举报处置 ══════════════════════
|
||
|
||
// adminHandleReportPUT 管理端举报处置。
|
||
// 契约:{action: 'dismiss'|'resolve_take_down'|..., handle_note}
|
||
func (d *Deps) adminHandleReportPUT(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Action string `json:"action"`
|
||
HandleNote string `json:"handle_note"`
|
||
}
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
if req.Action == "" {
|
||
req.Action = "resolve_take_down"
|
||
}
|
||
status := "handled"
|
||
if req.Action == "dismiss" {
|
||
status = "rejected"
|
||
}
|
||
|
||
reportID := chi.URLParam(r, "reportID")
|
||
var targetType, targetID string
|
||
err := d.Pool.QueryRow(r.Context(),
|
||
`SELECT target_type, target_id FROM reports WHERE id=$1`, reportID).Scan(&targetType, &targetID)
|
||
if err != nil {
|
||
httpx.WriteError(w, httpx.NotFound("举报不存在"))
|
||
return
|
||
}
|
||
|
||
if err := d.Reports.Handle(r.Context(), d.Pool, reportID,
|
||
middleware.UserID(r.Context()), req.HandleNote, status); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
|
||
// 处置动作要求下架时,对文章类举报目标执行下架
|
||
if status == "handled" && targetType == "article" {
|
||
if a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, targetID); err == nil && a.Status == domain.StatusPublished {
|
||
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
|
||
if err := d.Articles.UpdateStatus(r.Context(), tx, a.ID, domain.StatusOffline, a.ReviewStatus); err != nil {
|
||
return err
|
||
}
|
||
if err := d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "delete"); err != nil {
|
||
return err
|
||
}
|
||
return refreshTopicArticleCount(r.Context(), tx, a.TopicID)
|
||
})
|
||
if err == nil {
|
||
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
|
||
d.invalidateFeeds(r, a.CategoryID)
|
||
d.notify(r, a.OwnerID, middleware.UserID(r.Context()), "review", "article", a.ID,
|
||
"文章已被下架", "因举报核实违规,文章已被下架:"+req.HandleNote)
|
||
}
|
||
}
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
// ══════════════════════ 管理端:系统设置 ══════════════════════
|
||
|
||
func (d *Deps) adminGetSettings(w http.ResponseWriter, r *http.Request) {
|
||
kv, err := d.Settings.Get(r.Context(), d.Pool)
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
out := map[string]any{
|
||
"site_name": "多端长图文创作与运营平台",
|
||
"page_size": 10,
|
||
"audit_required": true,
|
||
"sensitive_words": "",
|
||
}
|
||
for k, v := range kv {
|
||
var anyv any
|
||
if json.Unmarshal(v, &anyv) == nil {
|
||
out[k] = anyv
|
||
}
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, out)
|
||
}
|
||
|
||
func (d *Deps) adminPutSettings(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
SiteName *string `json:"site_name"`
|
||
PageSize *int `json:"page_size"`
|
||
AuditRequired *bool `json:"audit_required"`
|
||
SensitiveWords *string `json:"sensitive_words"`
|
||
}
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
|
||
err := d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
|
||
if req.SiteName != nil {
|
||
if s := strings.TrimSpace(*req.SiteName); s != "" {
|
||
if err := d.Settings.Set(r.Context(), tx, "site_name", s); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
}
|
||
if req.PageSize != nil {
|
||
if *req.PageSize < 1 || *req.PageSize > 100 {
|
||
return httpx.InvalidParam("page_size 需在 1-100 之间")
|
||
}
|
||
if err := d.Settings.Set(r.Context(), tx, "page_size", *req.PageSize); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if req.AuditRequired != nil {
|
||
if err := d.Settings.Set(r.Context(), tx, "audit_required", *req.AuditRequired); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if req.SensitiveWords != nil {
|
||
if err := d.Settings.Set(r.Context(), tx, "sensitive_words", *req.SensitiveWords); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
return nil
|
||
})
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
// ══════════════════════ 管理端:分类/标签 ══════════════════════
|
||
|
||
type adminCategoryReq struct {
|
||
Name string `json:"name"`
|
||
Slug string `json:"slug"`
|
||
ParentID *string `json:"parent_id"`
|
||
SortOrder int `json:"sort_order"`
|
||
}
|
||
|
||
func (d *Deps) adminCreateCategory(w http.ResponseWriter, r *http.Request) {
|
||
var req adminCategoryReq
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
req.Name = strings.TrimSpace(req.Name)
|
||
req.Slug = strings.TrimSpace(req.Slug)
|
||
if req.Name == "" || req.Slug == "" {
|
||
httpx.WriteError(w, httpx.InvalidParam("name 与 slug 均为必填"))
|
||
return
|
||
}
|
||
if err := d.Taxonomy.UpsertCategory(r.Context(), d.Pool, newID(), req.Name, req.Slug, req.ParentID, req.SortOrder); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteCreated(w, map[string]any{"ok": true})
|
||
}
|
||
|
||
func (d *Deps) adminUpdateCategory(w http.ResponseWriter, r *http.Request) {
|
||
var req adminCategoryReq
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
req.Name = strings.TrimSpace(req.Name)
|
||
req.Slug = strings.TrimSpace(req.Slug)
|
||
if req.Name == "" || req.Slug == "" {
|
||
httpx.WriteError(w, httpx.InvalidParam("name 与 slug 均为必填"))
|
||
return
|
||
}
|
||
if err := d.Taxonomy.UpdateCategoryByID(r.Context(), d.Pool,
|
||
chi.URLParam(r, "categoryID"), req.Name, req.Slug, req.ParentID, req.SortOrder); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
func (d *Deps) adminDeleteCategory(w http.ResponseWriter, r *http.Request) {
|
||
if err := d.Taxonomy.DeleteCategory(r.Context(), d.Pool, chi.URLParam(r, "categoryID")); err != nil {
|
||
if err == repo.ErrNotFound {
|
||
httpx.WriteError(w, httpx.NotFound("分类不存在"))
|
||
return
|
||
}
|
||
httpx.WriteError(w, httpx.InvalidParam("无法删除:该分类下仍有子分类或文章在使用"))
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
// adminListTagsPaged 管理端标签分页列表
|
||
func (d *Deps) adminListTagsPaged(w http.ResponseWriter, r *http.Request) {
|
||
limit, offset := pageParams(r)
|
||
items, total, err := d.Taxonomy.ListTagsPaged(r.Context(), d.Pool,
|
||
strings.TrimSpace(r.URL.Query().Get("keyword")), limit, offset)
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total})
|
||
}
|
||
|
||
// adminTagAction 标签管理动作:create / toggle_status
|
||
func (d *Deps) adminTagAction(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Action string `json:"action"`
|
||
Name string `json:"name"`
|
||
TagID string `json:"tag_id"`
|
||
Status string `json:"status"`
|
||
}
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
switch req.Action {
|
||
case "create", "":
|
||
name := strings.TrimSpace(req.Name)
|
||
if name == "" {
|
||
httpx.WriteError(w, httpx.InvalidParam("标签名不能为空"))
|
||
return
|
||
}
|
||
if err := d.Taxonomy.UpsertTag(r.Context(), d.Pool, newID(), name); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteCreated(w, map[string]any{"ok": true})
|
||
case "toggle_status":
|
||
status := req.Status
|
||
// 表内合法值是 active|hidden,管理端语义 disabled 映射为 hidden
|
||
if status == "disabled" {
|
||
status = "hidden"
|
||
}
|
||
if status != "active" && status != "hidden" {
|
||
httpx.WriteError(w, httpx.InvalidParam("status 取值非法"))
|
||
return
|
||
}
|
||
if err := d.Taxonomy.SetTagStatus(r.Context(), d.Pool, req.TagID, status); err != nil {
|
||
if err == repo.ErrNotFound {
|
||
httpx.WriteError(w, httpx.NotFound("标签不存在"))
|
||
return
|
||
}
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
default:
|
||
httpx.WriteError(w, httpx.InvalidParam("action 取值非法"))
|
||
}
|
||
}
|
||
|
||
// ══════════════════════ 管理端:话题/用户 ══════════════════════
|
||
|
||
func (d *Deps) adminSetTopicStatus(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Status string `json:"status"`
|
||
}
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
switch req.Status {
|
||
case "active", "hidden", "disabled":
|
||
default:
|
||
httpx.WriteError(w, httpx.InvalidParam("status 只能是 active / hidden / disabled"))
|
||
return
|
||
}
|
||
_, err := d.Pool.Exec(r.Context(),
|
||
`UPDATE topics SET status=$2, updated_at=now() WHERE id=$1`,
|
||
chi.URLParam(r, "topicID"), req.Status)
|
||
if err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||
}
|
||
|
||
func (d *Deps) adminSetUserRole(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Role string `json:"role"`
|
||
}
|
||
if err := httpx.Decode(r, &req); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
switch rbac.Role(req.Role) {
|
||
case rbac.RoleUser, rbac.RoleAuthor, rbac.RoleReviewer, rbac.RoleOperator, rbac.RoleSuperAdmin:
|
||
default:
|
||
httpx.WriteError(w, httpx.InvalidParam(
|
||
"role 只能是 user / author / reviewer / operator / super_admin"))
|
||
return
|
||
}
|
||
targetID := chi.URLParam(r, "userID")
|
||
if targetID == middleware.UserID(r.Context()) {
|
||
httpx.WriteError(w, httpx.InvalidParam("不能修改自己的角色"))
|
||
return
|
||
}
|
||
if err := d.Users.UpdateRole(r.Context(), d.Pool, targetID, req.Role); err != nil {
|
||
httpx.WriteError(w, err)
|
||
return
|
||
}
|
||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "role": req.Role})
|
||
}
|
||
|
||
// ══════════════════════ 管理端:模板管理(/admin/templates) ══════════════════════
|
||
|
||
// adminCreateTemplate / adminUpdateTemplate / adminDeleteTemplate 直接复用
|
||
// v5_handlers 的 createTemplate / updateTemplate / deleteTemplate,
|
||
// 请求体由 templateReq 统一兼容 sections / sections_json 两种字段名。
|