feat: add tenant content management features for superadmin

- Implemented API endpoints for listing tenant contents and updating content status.
- Added Swagger documentation for new endpoints:
  - GET /super/v1/tenants/{tenantID}/contents
  - PATCH /super/v1/tenants/{tenantID}/contents/{contentID}/status
- Created DTOs for content item and status update form.
- Enhanced frontend to support content management in the tenant detail page.
- Added search and filter functionalities for tenant contents.
- Implemented unpublish functionality with confirmation dialog.
- Updated service layer to handle new content management logic.
This commit is contained in:
2025-12-24 16:10:07 +08:00
parent 8fa321dbf6
commit 568f5cda43
13 changed files with 1344 additions and 3 deletions

View File

@@ -0,0 +1,44 @@
package dto
import (
"strings"
"time"
"quyun/v2/app/requests"
"quyun/v2/database/models"
"quyun/v2/pkg/consts"
)
// TenantContentFilter defines list query filters for tenant contents (superadmin).
type TenantContentFilter struct {
requests.Pagination `json:",inline" query:",inline"`
requests.SortQueryFilter `json:",inline" query:",inline"`
Keyword *string `json:"keyword,omitempty" query:"keyword"`
Status *consts.ContentStatus `json:"status,omitempty" query:"status"`
Visibility *consts.ContentVisibility `json:"visibility,omitempty" query:"visibility"`
UserID *int64 `json:"user_id,omitempty" query:"user_id"`
PublishedAtFrom *time.Time `json:"published_at_from,omitempty" query:"published_at_from"`
PublishedAtTo *time.Time `json:"published_at_to,omitempty" query:"published_at_to"`
CreatedAtFrom *time.Time `json:"created_at_from,omitempty" query:"created_at_from"`
CreatedAtTo *time.Time `json:"created_at_to,omitempty" query:"created_at_to"`
}
func (f *TenantContentFilter) KeywordTrimmed() string {
if f == nil || f.Keyword == nil {
return ""
}
return strings.TrimSpace(*f.Keyword)
}
type SuperTenantContentItem struct {
Content *models.Content `json:"content,omitempty"`
Price *models.ContentPrice `json:"price,omitempty"`
Owner *SuperUserLite `json:"owner,omitempty"`
StatusDescription string `json:"status_description,omitempty"`
VisibilityDescription string `json:"visibility_description,omitempty"`
}

View File

@@ -0,0 +1,8 @@
package dto
import "quyun/v2/pkg/consts"
type SuperTenantContentStatusUpdateForm struct {
// Status supports: unpublished (下架) / blocked (封禁)
Status consts.ContentStatus `json:"status" validate:"required,oneof=unpublished blocked"`
}

View File

@@ -87,6 +87,12 @@ func (r *Routes) Register(router fiber.Router) {
r.tenant.detail, r.tenant.detail,
PathParam[int64]("tenantID"), PathParam[int64]("tenantID"),
)) ))
r.log.Debugf("Registering route: Get /super/v1/tenants/:tenantID<int>/contents -> tenant.contents")
router.Get("/super/v1/tenants/:tenantID<int>/contents"[len(r.Path()):], DataFunc2(
r.tenant.contents,
PathParam[int64]("tenantID"),
Query[dto.TenantContentFilter]("filter"),
))
r.log.Debugf("Registering route: Get /super/v1/tenants/:tenantID<int>/users -> tenant.users") r.log.Debugf("Registering route: Get /super/v1/tenants/:tenantID<int>/users -> tenant.users")
router.Get("/super/v1/tenants/:tenantID<int>/users"[len(r.Path()):], DataFunc2( router.Get("/super/v1/tenants/:tenantID<int>/users"[len(r.Path()):], DataFunc2(
r.tenant.users, r.tenant.users,
@@ -103,6 +109,13 @@ func (r *Routes) Register(router fiber.Router) {
PathParam[int64]("tenantID"), PathParam[int64]("tenantID"),
Body[dto.TenantExpireUpdateForm]("form"), Body[dto.TenantExpireUpdateForm]("form"),
)) ))
r.log.Debugf("Registering route: Patch /super/v1/tenants/:tenantID<int>/contents/:contentID<int>/status -> tenant.updateContentStatus")
router.Patch("/super/v1/tenants/:tenantID<int>/contents/:contentID<int>/status"[len(r.Path()):], DataFunc3(
r.tenant.updateContentStatus,
PathParam[int64]("tenantID"),
PathParam[int64]("contentID"),
Body[dto.SuperTenantContentStatusUpdateForm]("form"),
))
r.log.Debugf("Registering route: Patch /super/v1/tenants/:tenantID<int>/status -> tenant.updateStatus") r.log.Debugf("Registering route: Patch /super/v1/tenants/:tenantID<int>/status -> tenant.updateStatus")
router.Patch("/super/v1/tenants/:tenantID<int>/status"[len(r.Path()):], Func2( router.Patch("/super/v1/tenants/:tenantID<int>/status"[len(r.Path()):], Func2(
r.tenant.updateStatus, r.tenant.updateStatus,

View File

@@ -0,0 +1,30 @@
package super
import (
"quyun/v2/app/http/super/dto"
"quyun/v2/app/requests"
"quyun/v2/app/services"
"github.com/gofiber/fiber/v3"
)
// contents
//
// @Summary 租户内容列表(平台侧)
// @Tags Super
// @Accept json
// @Produce json
// @Param tenantID path int64 true "TenantID"
// @Param filter query dto.TenantContentFilter true "Filter"
// @Success 200 {object} requests.Pager{items=dto.SuperTenantContentItem}
//
// @Router /super/v1/tenants/:tenantID<int>/contents [get]
// @Bind tenantID path
// @Bind filter query
func (*tenant) contents(ctx fiber.Ctx, tenantID int64, filter *dto.TenantContentFilter) (*requests.Pager, error) {
if filter == nil {
filter = &dto.TenantContentFilter{}
}
filter.Pagination.Format()
return services.Content.SuperTenantContentsPage(ctx, tenantID, filter)
}

View File

@@ -0,0 +1,47 @@
package super
import (
"time"
"quyun/v2/app/errorx"
"quyun/v2/app/http/super/dto"
"quyun/v2/app/services"
"quyun/v2/database/models"
"quyun/v2/pkg/consts"
"quyun/v2/providers/jwt"
"github.com/gofiber/fiber/v3"
)
// updateContentStatus
//
// @Summary 更新租户内容状态(平台侧:下架/封禁)
// @Tags Super
// @Accept json
// @Produce json
// @Param tenantID path int64 true "TenantID"
// @Param contentID path int64 true "ContentID"
// @Param form body dto.SuperTenantContentStatusUpdateForm true "Form"
// @Success 200 {object} models.Content
//
// @Router /super/v1/tenants/:tenantID<int>/contents/:contentID<int>/status [patch]
// @Bind tenantID path
// @Bind contentID path
// @Bind form body
func (*tenant) updateContentStatus(
ctx fiber.Ctx,
tenantID int64,
contentID int64,
form *dto.SuperTenantContentStatusUpdateForm,
) (*models.Content, error) {
if form == nil {
return nil, errorx.ErrInvalidParameter
}
claims, ok := ctx.Locals(consts.CtxKeyClaims).(*jwt.Claims)
if !ok || claims == nil || claims.UserID <= 0 {
return nil, errorx.ErrTokenInvalid
}
return services.Content.SuperUpdateTenantContentStatus(ctx, claims.UserID, tenantID, contentID, form.Status, time.Now())
}

View File

@@ -0,0 +1,238 @@
package services
import (
"context"
"strings"
"time"
"quyun/v2/app/errorx"
superdto "quyun/v2/app/http/super/dto"
"quyun/v2/app/requests"
"quyun/v2/database"
"quyun/v2/database/models"
"quyun/v2/pkg/consts"
"github.com/pkg/errors"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"go.ipao.vip/gen"
"go.ipao.vip/gen/field"
)
// SuperTenantContentsPage returns tenant contents list for superadmin.
func (s *content) SuperTenantContentsPage(ctx context.Context, tenantID int64, filter *superdto.TenantContentFilter) (*requests.Pager, error) {
if tenantID <= 0 {
return nil, errors.New("tenant_id must be > 0")
}
if filter == nil {
filter = &superdto.TenantContentFilter{}
}
log.WithFields(log.Fields{
"tenant_id": tenantID,
"page": filter.Page,
"limit": filter.Limit,
}).Info("services.content.super_tenant_contents_page")
tbl, query := models.ContentQuery.QueryContext(ctx)
conds := []gen.Condition{
tbl.TenantID.Eq(tenantID),
tbl.DeletedAt.IsNull(),
}
if kw := strings.TrimSpace(filter.KeywordTrimmed()); kw != "" {
conds = append(conds, tbl.Title.Like(database.WrapLike(kw)))
}
if filter.Status != nil {
conds = append(conds, tbl.Status.Eq(*filter.Status))
}
if filter.Visibility != nil {
conds = append(conds, tbl.Visibility.Eq(*filter.Visibility))
}
if filter.UserID != nil && *filter.UserID > 0 {
conds = append(conds, tbl.UserID.Eq(*filter.UserID))
}
if filter.PublishedAtFrom != nil {
conds = append(conds, tbl.PublishedAt.Gte(*filter.PublishedAtFrom))
}
if filter.PublishedAtTo != nil {
conds = append(conds, tbl.PublishedAt.Lte(*filter.PublishedAtTo))
}
if filter.CreatedAtFrom != nil {
conds = append(conds, tbl.CreatedAt.Gte(*filter.CreatedAtFrom))
}
if filter.CreatedAtTo != nil {
conds = append(conds, tbl.CreatedAt.Lte(*filter.CreatedAtTo))
}
filter.Pagination.Format()
orderBys := make([]field.Expr, 0, 6)
allowedAsc := map[string]field.Expr{
"id": tbl.ID.Asc(),
"title": tbl.Title.Asc(),
"user_id": tbl.UserID.Asc(),
"status": tbl.Status.Asc(),
"visibility": tbl.Visibility.Asc(),
"published_at": tbl.PublishedAt.Asc(),
"created_at": tbl.CreatedAt.Asc(),
"updated_at": tbl.UpdatedAt.Asc(),
}
allowedDesc := map[string]field.Expr{
"id": tbl.ID.Desc(),
"title": tbl.Title.Desc(),
"user_id": tbl.UserID.Desc(),
"status": tbl.Status.Desc(),
"visibility": tbl.Visibility.Desc(),
"published_at": tbl.PublishedAt.Desc(),
"created_at": tbl.CreatedAt.Desc(),
"updated_at": tbl.UpdatedAt.Desc(),
}
for _, f := range filter.AscFields() {
f = strings.TrimSpace(f)
if f == "" {
continue
}
if ob, ok := allowedAsc[f]; ok {
orderBys = append(orderBys, ob)
}
}
for _, f := range filter.DescFields() {
f = strings.TrimSpace(f)
if f == "" {
continue
}
if ob, ok := allowedDesc[f]; ok {
orderBys = append(orderBys, ob)
}
}
if len(orderBys) == 0 {
orderBys = append(orderBys, tbl.ID.Desc())
} else {
orderBys = append(orderBys, tbl.ID.Desc())
}
items, total, err := query.Where(conds...).Order(orderBys...).FindByPage(int(filter.Offset()), int(filter.Limit))
if err != nil {
return nil, err
}
contentIDs := lo.Map(items, func(item *models.Content, _ int) int64 {
if item == nil {
return 0
}
return item.ID
})
contentIDs = lo.Filter(contentIDs, func(id int64, _ int) bool { return id > 0 })
priceByContent, err := s.contentPriceMapping(ctx, tenantID, contentIDs)
if err != nil {
return nil, err
}
ownerIDs := lo.Uniq(lo.FilterMap(items, func(item *models.Content, _ int) (int64, bool) {
if item == nil || item.UserID <= 0 {
return 0, false
}
return item.UserID, true
}))
ownerMap := map[int64]*superdto.SuperUserLite{}
if len(ownerIDs) > 0 {
uTbl, uQuery := models.UserQuery.QueryContext(ctx)
users, err := uQuery.Where(uTbl.ID.In(ownerIDs...)).Find()
if err != nil {
return nil, err
}
for _, u := range users {
if u == nil {
continue
}
ownerMap[u.ID] = &superdto.SuperUserLite{
ID: u.ID,
Username: u.Username,
Status: u.Status,
Roles: u.Roles,
VerifiedAt: u.VerifiedAt,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
StatusDescription: u.Status.Description(),
}
}
}
respItems := lo.Map(items, func(model *models.Content, _ int) *superdto.SuperTenantContentItem {
if model == nil {
return nil
}
return &superdto.SuperTenantContentItem{
Content: model,
Price: priceByContent[model.ID],
Owner: ownerMap[model.UserID],
StatusDescription: model.Status.Description(),
VisibilityDescription: model.Visibility.Description(),
}
})
return &requests.Pager{
Pagination: filter.Pagination,
Total: total,
Items: respItems,
}, nil
}
func (s *content) SuperUpdateTenantContentStatus(
ctx context.Context,
operatorUserID, tenantID, contentID int64,
status consts.ContentStatus,
now time.Time,
) (*models.Content, error) {
if operatorUserID <= 0 {
return nil, errorx.ErrTokenInvalid
}
if tenantID <= 0 {
return nil, errors.New("tenant_id must be > 0")
}
if contentID <= 0 {
return nil, errors.New("content_id must be > 0")
}
if status != consts.ContentStatusUnpublished && status != consts.ContentStatusBlocked {
return nil, errorx.ErrInvalidParameter.WithMsg("invalid status")
}
log.WithFields(log.Fields{
"operator_user_id": operatorUserID,
"tenant_id": tenantID,
"content_id": contentID,
"status": status,
}).Info("services.content.super_update_tenant_content_status")
tbl, query := models.ContentQuery.QueryContext(ctx)
model, err := query.Where(
tbl.TenantID.Eq(tenantID),
tbl.ID.Eq(contentID),
tbl.DeletedAt.IsNull(),
).First()
if err != nil {
return nil, err
}
if status == consts.ContentStatusUnpublished && model.Status != consts.ContentStatusPublished {
return nil, errorx.ErrPreconditionFailed.WithMsg("content is not published")
}
if _, err := query.Where(
tbl.TenantID.Eq(tenantID),
tbl.ID.Eq(contentID),
tbl.DeletedAt.IsNull(),
).UpdateSimple(
tbl.Status.Value(status),
); err != nil {
return nil, err
}
model.Status = status
model.UpdatedAt = now
return model, nil
}

View File

@@ -570,6 +570,187 @@ const docTemplate = `{
"responses": {} "responses": {}
} }
}, },
"/super/v1/tenants/{tenantID}/contents": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Super"
],
"summary": "租户内容列表(平台侧)",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "TenantID",
"name": "tenantID",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Asc specifies comma-separated field names to sort ascending by.",
"name": "asc",
"in": "query"
},
{
"type": "string",
"name": "created_at_from",
"in": "query"
},
{
"type": "string",
"name": "created_at_to",
"in": "query"
},
{
"type": "string",
"description": "Desc specifies comma-separated field names to sort descending by.",
"name": "desc",
"in": "query"
},
{
"type": "string",
"name": "keyword",
"in": "query"
},
{
"type": "integer",
"description": "Limit is page size; only values in {10,20,50,100} are accepted (otherwise defaults to 10).",
"name": "limit",
"in": "query"
},
{
"type": "integer",
"description": "Page is 1-based page index; values \u003c= 0 are normalized to 1.",
"name": "page",
"in": "query"
},
{
"type": "string",
"name": "published_at_from",
"in": "query"
},
{
"type": "string",
"name": "published_at_to",
"in": "query"
},
{
"enum": [
"draft",
"reviewing",
"published",
"unpublished",
"blocked"
],
"type": "string",
"x-enum-varnames": [
"ContentStatusDraft",
"ContentStatusReviewing",
"ContentStatusPublished",
"ContentStatusUnpublished",
"ContentStatusBlocked"
],
"name": "status",
"in": "query"
},
{
"type": "integer",
"name": "user_id",
"in": "query"
},
{
"enum": [
"public",
"tenant_only",
"private"
],
"type": "string",
"x-enum-varnames": [
"ContentVisibilityPublic",
"ContentVisibilityTenantOnly",
"ContentVisibilityPrivate"
],
"name": "visibility",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"allOf": [
{
"$ref": "#/definitions/requests.Pager"
},
{
"type": "object",
"properties": {
"items": {
"$ref": "#/definitions/dto.SuperTenantContentItem"
}
}
}
]
}
}
}
}
},
"/super/v1/tenants/{tenantID}/contents/{contentID}/status": {
"patch": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Super"
],
"summary": "更新租户内容状态(平台侧:下架/封禁)",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "TenantID",
"name": "tenantID",
"in": "path",
"required": true
},
{
"type": "integer",
"format": "int64",
"description": "ContentID",
"name": "contentID",
"in": "path",
"required": true
},
{
"description": "Form",
"name": "form",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/dto.SuperTenantContentStatusUpdateForm"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/models.Content"
}
}
}
}
},
"/super/v1/tenants/{tenantID}/status": { "/super/v1/tenants/{tenantID}/status": {
"patch": { "patch": {
"consumes": [ "consumes": [
@@ -4364,6 +4545,46 @@ const docTemplate = `{
} }
} }
}, },
"dto.SuperTenantContentItem": {
"type": "object",
"properties": {
"content": {
"$ref": "#/definitions/models.Content"
},
"owner": {
"$ref": "#/definitions/dto.SuperUserLite"
},
"price": {
"$ref": "#/definitions/models.ContentPrice"
},
"status_description": {
"type": "string"
},
"visibility_description": {
"type": "string"
}
}
},
"dto.SuperTenantContentStatusUpdateForm": {
"type": "object",
"required": [
"status"
],
"properties": {
"status": {
"description": "Status supports: unpublished (下架) / blocked (封禁)",
"enum": [
"unpublished",
"blocked"
],
"allOf": [
{
"$ref": "#/definitions/consts.ContentStatus"
}
]
}
}
},
"dto.SuperTenantUserItem": { "dto.SuperTenantUserItem": {
"type": "object", "type": "object",
"properties": { "properties": {

View File

@@ -564,6 +564,187 @@
"responses": {} "responses": {}
} }
}, },
"/super/v1/tenants/{tenantID}/contents": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Super"
],
"summary": "租户内容列表(平台侧)",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "TenantID",
"name": "tenantID",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Asc specifies comma-separated field names to sort ascending by.",
"name": "asc",
"in": "query"
},
{
"type": "string",
"name": "created_at_from",
"in": "query"
},
{
"type": "string",
"name": "created_at_to",
"in": "query"
},
{
"type": "string",
"description": "Desc specifies comma-separated field names to sort descending by.",
"name": "desc",
"in": "query"
},
{
"type": "string",
"name": "keyword",
"in": "query"
},
{
"type": "integer",
"description": "Limit is page size; only values in {10,20,50,100} are accepted (otherwise defaults to 10).",
"name": "limit",
"in": "query"
},
{
"type": "integer",
"description": "Page is 1-based page index; values \u003c= 0 are normalized to 1.",
"name": "page",
"in": "query"
},
{
"type": "string",
"name": "published_at_from",
"in": "query"
},
{
"type": "string",
"name": "published_at_to",
"in": "query"
},
{
"enum": [
"draft",
"reviewing",
"published",
"unpublished",
"blocked"
],
"type": "string",
"x-enum-varnames": [
"ContentStatusDraft",
"ContentStatusReviewing",
"ContentStatusPublished",
"ContentStatusUnpublished",
"ContentStatusBlocked"
],
"name": "status",
"in": "query"
},
{
"type": "integer",
"name": "user_id",
"in": "query"
},
{
"enum": [
"public",
"tenant_only",
"private"
],
"type": "string",
"x-enum-varnames": [
"ContentVisibilityPublic",
"ContentVisibilityTenantOnly",
"ContentVisibilityPrivate"
],
"name": "visibility",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"allOf": [
{
"$ref": "#/definitions/requests.Pager"
},
{
"type": "object",
"properties": {
"items": {
"$ref": "#/definitions/dto.SuperTenantContentItem"
}
}
}
]
}
}
}
}
},
"/super/v1/tenants/{tenantID}/contents/{contentID}/status": {
"patch": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Super"
],
"summary": "更新租户内容状态(平台侧:下架/封禁)",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "TenantID",
"name": "tenantID",
"in": "path",
"required": true
},
{
"type": "integer",
"format": "int64",
"description": "ContentID",
"name": "contentID",
"in": "path",
"required": true
},
{
"description": "Form",
"name": "form",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/dto.SuperTenantContentStatusUpdateForm"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/models.Content"
}
}
}
}
},
"/super/v1/tenants/{tenantID}/status": { "/super/v1/tenants/{tenantID}/status": {
"patch": { "patch": {
"consumes": [ "consumes": [
@@ -4358,6 +4539,46 @@
} }
} }
}, },
"dto.SuperTenantContentItem": {
"type": "object",
"properties": {
"content": {
"$ref": "#/definitions/models.Content"
},
"owner": {
"$ref": "#/definitions/dto.SuperUserLite"
},
"price": {
"$ref": "#/definitions/models.ContentPrice"
},
"status_description": {
"type": "string"
},
"visibility_description": {
"type": "string"
}
}
},
"dto.SuperTenantContentStatusUpdateForm": {
"type": "object",
"required": [
"status"
],
"properties": {
"status": {
"description": "Status supports: unpublished (下架) / blocked (封禁)",
"enum": [
"unpublished",
"blocked"
],
"allOf": [
{
"$ref": "#/definitions/consts.ContentStatus"
}
]
}
}
},
"dto.SuperTenantUserItem": { "dto.SuperTenantUserItem": {
"type": "object", "type": "object",
"properties": { "properties": {

View File

@@ -704,6 +704,31 @@ definitions:
description: Reason is the human-readable refund reason used for audit. description: Reason is the human-readable refund reason used for audit.
type: string type: string
type: object type: object
dto.SuperTenantContentItem:
properties:
content:
$ref: '#/definitions/models.Content'
owner:
$ref: '#/definitions/dto.SuperUserLite'
price:
$ref: '#/definitions/models.ContentPrice'
status_description:
type: string
visibility_description:
type: string
type: object
dto.SuperTenantContentStatusUpdateForm:
properties:
status:
allOf:
- $ref: '#/definitions/consts.ContentStatus'
description: 'Status supports: unpublished (下架) / blocked (封禁)'
enum:
- unpublished
- blocked
required:
- status
type: object
dto.SuperTenantUserItem: dto.SuperTenantUserItem:
properties: properties:
tenant_user: tenant_user:
@@ -1835,6 +1860,127 @@ paths:
summary: 更新过期时间 summary: 更新过期时间
tags: tags:
- Super - Super
/super/v1/tenants/{tenantID}/contents:
get:
consumes:
- application/json
parameters:
- description: TenantID
format: int64
in: path
name: tenantID
required: true
type: integer
- description: Asc specifies comma-separated field names to sort ascending by.
in: query
name: asc
type: string
- in: query
name: created_at_from
type: string
- in: query
name: created_at_to
type: string
- description: Desc specifies comma-separated field names to sort descending
by.
in: query
name: desc
type: string
- in: query
name: keyword
type: string
- description: Limit is page size; only values in {10,20,50,100} are accepted
(otherwise defaults to 10).
in: query
name: limit
type: integer
- description: Page is 1-based page index; values <= 0 are normalized to 1.
in: query
name: page
type: integer
- in: query
name: published_at_from
type: string
- in: query
name: published_at_to
type: string
- enum:
- draft
- reviewing
- published
- unpublished
- blocked
in: query
name: status
type: string
x-enum-varnames:
- ContentStatusDraft
- ContentStatusReviewing
- ContentStatusPublished
- ContentStatusUnpublished
- ContentStatusBlocked
- in: query
name: user_id
type: integer
- enum:
- public
- tenant_only
- private
in: query
name: visibility
type: string
x-enum-varnames:
- ContentVisibilityPublic
- ContentVisibilityTenantOnly
- ContentVisibilityPrivate
produces:
- application/json
responses:
"200":
description: OK
schema:
allOf:
- $ref: '#/definitions/requests.Pager'
- properties:
items:
$ref: '#/definitions/dto.SuperTenantContentItem'
type: object
summary: 租户内容列表(平台侧)
tags:
- Super
/super/v1/tenants/{tenantID}/contents/{contentID}/status:
patch:
consumes:
- application/json
parameters:
- description: TenantID
format: int64
in: path
name: tenantID
required: true
type: integer
- description: ContentID
format: int64
in: path
name: contentID
required: true
type: integer
- description: Form
in: body
name: form
required: true
schema:
$ref: '#/definitions/dto.SuperTenantContentStatusUpdateForm'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/models.Content'
summary: 更新租户内容状态(平台侧:下架/封禁)
tags:
- Super
/super/v1/tenants/{tenantID}/status: /super/v1/tenants/{tenantID}/status:
patch: patch:
consumes: consumes:

View File

@@ -33,7 +33,7 @@
- 订单详情(含 items / snapshot 展示) - 订单详情(含 items / snapshot 展示)
- 平台侧退款(支持强制退款,记录操作人) - 平台侧退款(支持强制退款,记录操作人)
3) **租户管理增强** 3) **租户管理增强**
- 租户详情页(基本信息、过期续期、状态变更、管理员/成员管理) - 租户详情页(基本信息、过期续期、状态变更、管理员/成员/内容管理)
4) **用户管理增强** 4) **用户管理增强**
- 用户详情页(角色、状态、余额/冻结、加入/拥有的租户、操作记录) - 用户详情页(角色、状态、余额/冻结、加入/拥有的租户、操作记录)
- 角色授予/回收(`super_admin` - 角色授予/回收(`super_admin`

View File

@@ -7,8 +7,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sakai Vue</title> <title>Sakai Vue</title>
<link href="https://fonts.cdnfonts.com/css/lato" rel="stylesheet"> <link href="https://fonts.cdnfonts.com/css/lato" rel="stylesheet">
<script type="module" crossorigin src="./assets/index-0nqd4PcY.js"></script> <script type="module" crossorigin src="./assets/index-PWlTeOhw.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DMfJH3M_.css"> <link rel="stylesheet" crossorigin href="./assets/index-B8J4fGz4.css">
</head> </head>
<body> <body>

View File

@@ -0,0 +1,70 @@
import { requestJson } from './apiClient';
function normalizeItems(items) {
if (Array.isArray(items)) return items;
if (items && typeof items === 'object') return [items];
return [];
}
export const ContentService = {
async listTenantContents(
tenantID,
{
page,
limit,
keyword,
status,
visibility,
user_id,
published_at_from,
published_at_to,
created_at_from,
created_at_to,
sortField,
sortOrder
} = {}
) {
if (!tenantID) throw new Error('tenantID is required');
const iso = (d) => {
if (!d) return undefined;
const date = d instanceof Date ? d : new Date(d);
if (Number.isNaN(date.getTime())) return undefined;
return date.toISOString();
};
const query = {
page,
limit,
keyword,
status,
visibility,
user_id,
published_at_from: iso(published_at_from),
published_at_to: iso(published_at_to),
created_at_from: iso(created_at_from),
created_at_to: iso(created_at_to)
};
if (sortField && sortOrder) {
if (sortOrder === 1) query.asc = sortField;
if (sortOrder === -1) query.desc = sortField;
}
const data = await requestJson(`/super/v1/tenants/${tenantID}/contents`, { query });
return {
page: data?.page ?? page ?? 1,
limit: data?.limit ?? limit ?? 10,
total: data?.total ?? 0,
items: normalizeItems(data?.items)
};
}
,
async updateTenantContentStatus(tenantID, contentID, { status } = {}) {
if (!tenantID) throw new Error('tenantID is required');
if (!contentID) throw new Error('contentID is required');
return requestJson(`/super/v1/tenants/${tenantID}/contents/${contentID}/status`, {
method: 'PATCH',
body: { status }
});
}
};

View File

@@ -1,6 +1,7 @@
<script setup> <script setup>
import SearchField from '@/components/SearchField.vue'; import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue'; import SearchPanel from '@/components/SearchPanel.vue';
import { ContentService } from '@/service/ContentService';
import { OrderService } from '@/service/OrderService'; import { OrderService } from '@/service/OrderService';
import { TenantService } from '@/service/TenantService'; import { TenantService } from '@/service/TenantService';
import { useToast } from 'primevue/usetoast'; import { useToast } from 'primevue/usetoast';
@@ -57,6 +58,34 @@ function getOrderStatusSeverity(value) {
} }
} }
function getContentStatusSeverity(value) {
switch (value) {
case 'published':
return 'success';
case 'reviewing':
return 'warn';
case 'blocked':
return 'danger';
case 'draft':
case 'unpublished':
default:
return 'secondary';
}
}
function getContentVisibilitySeverity(value) {
switch (value) {
case 'public':
return 'info';
case 'tenant_only':
return 'warn';
case 'private':
return 'secondary';
default:
return 'secondary';
}
}
async function loadTenant() { async function loadTenant() {
const id = tenantID.value; const id = tenantID.value;
if (!id || Number.isNaN(id)) return; if (!id || Number.isNaN(id)) return;
@@ -123,6 +152,33 @@ const durationOptions = [
{ label: '365 天', value: 365 } { label: '365 天', value: 365 }
]; ];
const unpublishDialogVisible = ref(false);
const unpublishLoading = ref(false);
const unpublishItem = ref(null);
function openUnpublishDialog(row) {
unpublishItem.value = row;
unpublishDialogVisible.value = true;
}
async function confirmUnpublish() {
const id = tenantID.value;
const contentID = unpublishItem.value?.content?.id;
if (!id || !contentID) return;
unpublishLoading.value = true;
try {
await ContentService.updateTenantContentStatus(id, contentID, { status: 'unpublished' });
toast.add({ severity: 'success', summary: '下架成功', detail: `ContentID: ${contentID}`, life: 3000 });
unpublishDialogVisible.value = false;
await loadContents();
} catch (error) {
toast.add({ severity: 'error', summary: '下架失败', detail: error?.message || '无法下架内容', life: 4000 });
} finally {
unpublishLoading.value = false;
}
}
async function confirmRenew() { async function confirmRenew() {
const id = tenantID.value; const id = tenantID.value;
if (!id) return; if (!id) return;
@@ -201,6 +257,100 @@ function onTenantUsersPageChange(event) {
loadTenantUsers(); loadTenantUsers();
} }
const contentsLoading = ref(false);
const contents = ref([]);
const contentsTotal = ref(0);
const contentsPage = ref(1);
const contentsRows = ref(10);
const contentsKeyword = ref('');
const contentsStatus = ref('published');
const contentsVisibility = ref('');
const contentsOwnerUserID = ref(null);
const contentsPublishedAtFrom = ref(null);
const contentsPublishedAtTo = ref(null);
const contentsCreatedAtFrom = ref(null);
const contentsCreatedAtTo = ref(null);
const contentsSortField = ref('id');
const contentsSortOrder = ref(-1);
const contentStatusOptions = [
{ label: '全部', value: '' },
{ label: 'draft', value: 'draft' },
{ label: 'reviewing', value: 'reviewing' },
{ label: 'published', value: 'published' },
{ label: 'unpublished', value: 'unpublished' },
{ label: 'blocked', value: 'blocked' }
];
const contentVisibilityOptions = [
{ label: '全部', value: '' },
{ label: 'public', value: 'public' },
{ label: 'tenant_only', value: 'tenant_only' },
{ label: 'private', value: 'private' }
];
async function loadContents() {
const id = tenantID.value;
if (!id) return;
contentsLoading.value = true;
try {
const result = await ContentService.listTenantContents(id, {
page: contentsPage.value,
limit: contentsRows.value,
keyword: contentsKeyword.value,
status: contentsStatus.value || undefined,
visibility: contentsVisibility.value || undefined,
user_id: contentsOwnerUserID.value || undefined,
published_at_from: contentsPublishedAtFrom.value || undefined,
published_at_to: contentsPublishedAtTo.value || undefined,
created_at_from: contentsCreatedAtFrom.value || undefined,
created_at_to: contentsCreatedAtTo.value || undefined,
sortField: contentsSortField.value,
sortOrder: contentsSortOrder.value
});
contents.value = (result.items || []).map((item) => ({ ...item, __key: item?.content?.id ?? undefined }));
contentsTotal.value = result.total;
} catch (error) {
toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载租户内容列表', life: 4000 });
} finally {
contentsLoading.value = false;
}
}
function onContentsSearch() {
contentsPage.value = 1;
loadContents();
}
function onContentsReset() {
contentsKeyword.value = '';
contentsStatus.value = 'published';
contentsVisibility.value = '';
contentsOwnerUserID.value = null;
contentsPublishedAtFrom.value = null;
contentsPublishedAtTo.value = null;
contentsCreatedAtFrom.value = null;
contentsCreatedAtTo.value = null;
contentsSortField.value = 'id';
contentsSortOrder.value = -1;
contentsPage.value = 1;
contentsRows.value = 10;
loadContents();
}
function onContentsPage(event) {
contentsPage.value = (event.page ?? 0) + 1;
contentsRows.value = event.rows ?? contentsRows.value;
loadContents();
}
function onContentsSort(event) {
contentsSortField.value = event.sortField ?? contentsSortField.value;
contentsSortOrder.value = event.sortOrder ?? contentsSortOrder.value;
loadContents();
}
const ordersLoading = ref(false); const ordersLoading = ref(false);
const orders = ref([]); const orders = ref([]);
const ordersTotal = ref(0); const ordersTotal = ref(0);
@@ -295,10 +445,13 @@ watch(
() => { () => {
tenantUsersPage.value = 1; tenantUsersPage.value = 1;
tenantUsersRows.value = 10; tenantUsersRows.value = 10;
contentsPage.value = 1;
contentsRows.value = 10;
ordersPage.value = 1; ordersPage.value = 1;
ordersRows.value = 10; ordersRows.value = 10;
loadTenant(); loadTenant();
loadTenantUsers(); loadTenantUsers();
loadContents();
loadOrders(); loadOrders();
}, },
{ immediate: true } { immediate: true }
@@ -373,6 +526,7 @@ onMounted(() => {
<Tabs v-model:value="tabValue" value="users"> <Tabs v-model:value="tabValue" value="users">
<TabList> <TabList>
<Tab value="users">成员</Tab> <Tab value="users">成员</Tab>
<Tab value="contents">内容</Tab>
<Tab value="orders">订单</Tab> <Tab value="orders">订单</Tab>
</TabList> </TabList>
<TabPanels> <TabPanels>
@@ -473,6 +627,138 @@ onMounted(() => {
</DataTable> </DataTable>
</div> </div>
</TabPanel> </TabPanel>
<TabPanel value="contents">
<div class="flex flex-col gap-4">
<SearchPanel :loading="contentsLoading" @search="onContentsSearch" @reset="onContentsReset">
<SearchField label="Keyword">
<IconField>
<InputIcon>
<i class="pi pi-search" />
</InputIcon>
<InputText v-model="contentsKeyword" placeholder="标题关键词" class="w-full" @keyup.enter="onContentsSearch" />
</IconField>
</SearchField>
<SearchField label="状态">
<Select v-model="contentsStatus" :options="contentStatusOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
</SearchField>
<SearchField label="可见性">
<Select
v-model="contentsVisibility"
:options="contentVisibilityOptions"
optionLabel="label"
optionValue="value"
placeholder="请选择"
class="w-full"
/>
</SearchField>
<SearchField label="OwnerUserID">
<InputNumber v-model="contentsOwnerUserID" :min="1" placeholder="精确匹配" class="w-full" />
</SearchField>
<SearchField label="发布时间 From">
<DatePicker v-model="contentsPublishedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
</SearchField>
<SearchField label="发布时间 To">
<DatePicker v-model="contentsPublishedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
</SearchField>
<SearchField label="创建时间 From">
<DatePicker v-model="contentsCreatedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
</SearchField>
<SearchField label="创建时间 To">
<DatePicker v-model="contentsCreatedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
</SearchField>
</SearchPanel>
<DataTable
:value="contents"
dataKey="__key"
:loading="contentsLoading"
lazy
:paginator="true"
:rows="contentsRows"
:totalRecords="contentsTotal"
:first="(contentsPage - 1) * contentsRows"
:rowsPerPageOptions="[10, 20, 50, 100]"
sortMode="single"
:sortField="contentsSortField"
:sortOrder="contentsSortOrder"
@page="onContentsPage"
@sort="onContentsSort"
currentPageReportTemplate="显示第 {first} - {last} 条,共 {totalRecords} 条"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
scrollable
scrollHeight="520px"
responsiveLayout="scroll"
>
<Column header="ID" sortable sortField="id" style="min-width: 8rem">
<template #body="{ data }">
<span class="text-muted-color">{{ data?.content?.id ?? '-' }}</span>
</template>
</Column>
<Column header="标题" sortable sortField="title" style="min-width: 22rem">
<template #body="{ data }">
<div class="flex flex-col">
<span class="font-medium truncate max-w-[520px]">{{ data?.content?.title ?? '-' }}</span>
<span class="text-muted-color">ContentID: {{ data?.content?.id ?? '-' }}</span>
</div>
</template>
</Column>
<Column header="Owner" sortable sortField="user_id" style="min-width: 14rem">
<template #body="{ data }">
<div class="flex flex-col">
<span class="font-medium">{{ data?.owner?.username ?? '-' }}</span>
<span class="text-muted-color">ID: {{ data?.content?.user_id ?? '-' }}</span>
</div>
</template>
</Column>
<Column header="状态" sortable sortField="status" style="min-width: 12rem">
<template #body="{ data }">
<Tag :value="data?.status_description || data?.content?.status || '-'" :severity="getContentStatusSeverity(data?.content?.status)" />
</template>
</Column>
<Column header="可见性" sortable sortField="visibility" style="min-width: 12rem">
<template #body="{ data }">
<Tag
:value="data?.visibility_description || data?.content?.visibility || '-'"
:severity="getContentVisibilitySeverity(data?.content?.visibility)"
/>
</template>
</Column>
<Column header="价格" style="min-width: 10rem">
<template #body="{ data }">
<span v-if="data?.price && (data.price.price_amount ?? null) !== null">
{{ Number(data.price.price_amount) === 0 ? '免费' : formatCny(data.price.price_amount) }}
</span>
<span v-else class="text-muted-color">-</span>
</template>
</Column>
<Column header="发布时间" sortable sortField="published_at" style="min-width: 14rem">
<template #body="{ data }">
{{ formatDate(data?.content?.published_at) }}
</template>
</Column>
<Column header="创建时间" sortable sortField="created_at" style="min-width: 14rem">
<template #body="{ data }">
{{ formatDate(data?.content?.created_at) }}
</template>
</Column>
<Column header="操作" style="min-width: 10rem">
<template #body="{ data }">
<Button
v-if="data?.content?.status === 'published'"
label="下架"
icon="pi pi-ban"
severity="danger"
text
size="small"
class="p-0"
@click="openUnpublishDialog(data)"
/>
<span v-else class="text-muted-color">-</span>
</template>
</Column>
</DataTable>
</div>
</TabPanel>
<TabPanel value="orders"> <TabPanel value="orders">
<div class="flex flex-col gap-4"> <div class="flex flex-col gap-4">
<SearchPanel :loading="ordersLoading" @search="onOrdersSearch" @reset="onOrdersReset"> <SearchPanel :loading="ordersLoading" @search="onOrdersSearch" @reset="onOrdersReset">
@@ -606,4 +892,21 @@ onMounted(() => {
<Button label="确认" icon="pi pi-check" @click="confirmRenew" :loading="renewing" /> <Button label="确认" icon="pi pi-check" @click="confirmRenew" :loading="renewing" />
</template> </template>
</Dialog> </Dialog>
<Dialog v-model:visible="unpublishDialogVisible" :modal="true" :style="{ width: '460px' }">
<template #header>
<div class="flex items-center gap-2">
<span class="font-medium">下架内容</span>
<span class="text-muted-color truncate max-w-[280px]">{{ unpublishItem?.content?.title ?? '-' }}</span>
</div>
</template>
<div class="flex flex-col gap-2">
<div class="text-muted-color">确认将该内容下架下架后租户端将不可见/不可购买</div>
<div class="text-sm text-muted-color">ContentID: {{ unpublishItem?.content?.id ?? '-' }}</div>
</div>
<template #footer>
<Button label="取消" icon="pi pi-times" text @click="unpublishDialogVisible = false" :disabled="unpublishLoading" />
<Button label="确认下架" icon="pi pi-ban" severity="danger" @click="confirmUnpublish" :loading="unpublishLoading" />
</template>
</Dialog>
</template> </template>