Refactor brand service and related components
- Removed ListQuestionVersions method and associated types from BrandService and Queries. - Updated PromptRuleGenerationService to change task naming and handling. - Enhanced ScheduleTaskService to support filtering by created date range and keyword. - Introduced InstantTaskService for managing instant tasks with appropriate filtering and response structures. - Added InstantTaskHandler for handling API requests related to instant tasks. - Created InstantTaskTab component for the admin web interface to display and manage instant tasks. - Updated database migrations to rename source types for articles and generation tasks. - Adjusted models and repository queries to reflect the removal of question version handling.
This commit is contained in:
@@ -31,6 +31,7 @@ type ArticleListParams struct {
|
||||
GenerateStatus *string
|
||||
PublishStatus *string
|
||||
SourceType *string
|
||||
GenerationMode *string
|
||||
TemplateID *int64
|
||||
PromptRuleID *int64
|
||||
Keyword *string
|
||||
@@ -45,6 +46,7 @@ type ArticleListItem struct {
|
||||
TemplateName *string `json:"template_name"`
|
||||
PromptRuleID *int64 `json:"prompt_rule_id"`
|
||||
PromptRuleName *string `json:"prompt_rule_name"`
|
||||
GenerationMode *string `json:"generation_mode"`
|
||||
Platforms []string `json:"platforms"`
|
||||
GenerateStatus string `json:"generate_status"`
|
||||
PublishStatus string `json:"publish_status"`
|
||||
@@ -64,6 +66,7 @@ type ArticleListResponse struct {
|
||||
|
||||
func (s *ArticleService) List(ctx context.Context, params ArticleListParams) (*ArticleListResponse, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
sourceType := params.SourceType
|
||||
|
||||
if params.Page < 1 {
|
||||
params.Page = 1
|
||||
@@ -99,9 +102,14 @@ func (s *ArticleService) List(ctx context.Context, params ArticleListParams) (*A
|
||||
countArgs = append(countArgs, *params.PublishStatus)
|
||||
argIdx++
|
||||
}
|
||||
if params.SourceType != nil {
|
||||
if sourceType != nil {
|
||||
countQuery += ` AND a.source_type = $` + strconv.Itoa(argIdx)
|
||||
countArgs = append(countArgs, *params.SourceType)
|
||||
countArgs = append(countArgs, *sourceType)
|
||||
argIdx++
|
||||
}
|
||||
if params.GenerationMode != nil {
|
||||
countQuery += ` AND a.source_type = 'custom_generation' AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), 'instant') = $` + strconv.Itoa(argIdx)
|
||||
countArgs = append(countArgs, *params.GenerationMode)
|
||||
argIdx++
|
||||
}
|
||||
if params.TemplateID != nil {
|
||||
@@ -162,9 +170,14 @@ func (s *ArticleService) List(ctx context.Context, params ArticleListParams) (*A
|
||||
listArgs = append(listArgs, *params.PublishStatus)
|
||||
listIdx++
|
||||
}
|
||||
if params.SourceType != nil {
|
||||
if sourceType != nil {
|
||||
listQuery += ` AND a.source_type = $` + strconv.Itoa(listIdx)
|
||||
listArgs = append(listArgs, *params.SourceType)
|
||||
listArgs = append(listArgs, *sourceType)
|
||||
listIdx++
|
||||
}
|
||||
if params.GenerationMode != nil {
|
||||
listQuery += ` AND a.source_type = 'custom_generation' AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), 'instant') = $` + strconv.Itoa(listIdx)
|
||||
listArgs = append(listArgs, *params.GenerationMode)
|
||||
listIdx++
|
||||
}
|
||||
if params.TemplateID != nil {
|
||||
@@ -205,13 +218,16 @@ func (s *ArticleService) List(ctx context.Context, params ArticleListParams) (*A
|
||||
var items []ArticleListItem
|
||||
for rows.Next() {
|
||||
var item ArticleListItem
|
||||
var dbSourceType string
|
||||
var markdownContent *string
|
||||
var wizardStateJSON []byte
|
||||
var inputParamsJSON []byte
|
||||
if err := rows.Scan(&item.ID, &item.SourceType, &item.TemplateID, &item.PromptRuleID, &item.GenerateStatus, &item.PublishStatus, &item.CreatedAt,
|
||||
if err := rows.Scan(&item.ID, &dbSourceType, &item.TemplateID, &item.PromptRuleID, &item.GenerateStatus, &item.PublishStatus, &item.CreatedAt,
|
||||
&item.Title, &item.GenerationErrorMessage, &markdownContent, &item.WordCount, &item.SourceLabel, &item.TemplateName, &item.PromptRuleName, &wizardStateJSON, &inputParamsJSON); err != nil {
|
||||
return nil, response.ErrInternal(50010, "scan_failed", err.Error())
|
||||
}
|
||||
item.SourceType = dbSourceType
|
||||
item.GenerationMode = resolveArticleGenerationMode(dbSourceType, inputParamsJSON)
|
||||
item.Platforms = resolveArticlePlatforms(wizardStateJSON, inputParamsJSON)
|
||||
item.WordCount = resolveWordCount(markdownContent, item.WordCount)
|
||||
items = append(items, item)
|
||||
@@ -228,6 +244,7 @@ type ArticleDetailResponse struct {
|
||||
SourceType string `json:"source_type"`
|
||||
TemplateID *int64 `json:"template_id"`
|
||||
TemplateName *string `json:"template_name"`
|
||||
GenerationMode *string `json:"generation_mode"`
|
||||
Platforms []string `json:"platforms"`
|
||||
GenerateStatus string `json:"generate_status"`
|
||||
PublishStatus string `json:"publish_status"`
|
||||
@@ -245,6 +262,7 @@ type ArticleDetailResponse struct {
|
||||
func (s *ArticleService) Detail(ctx context.Context, id int64) (*ArticleDetailResponse, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
var d ArticleDetailResponse
|
||||
var dbSourceType string
|
||||
|
||||
var wizardStateJSON []byte
|
||||
var inputParamsJSON []byte
|
||||
@@ -263,15 +281,17 @@ func (s *ArticleService) Detail(ctx context.Context, id int64) (*ArticleDetailRe
|
||||
LIMIT 1
|
||||
) gt ON true
|
||||
WHERE a.id = $1 AND a.tenant_id = $2 AND a.deleted_at IS NULL
|
||||
`, id, actor.TenantID).Scan(&d.ID, &d.SourceType, &d.TemplateID, &d.GenerateStatus, &d.PublishStatus, &d.CreatedAt,
|
||||
`, id, actor.TenantID).Scan(&d.ID, &dbSourceType, &d.TemplateID, &d.GenerateStatus, &d.PublishStatus, &d.CreatedAt,
|
||||
&d.Title, &d.HTMLContent, &d.MarkdownContent, &d.WordCount, &d.SourceLabel, &d.VersionNo, &d.TemplateName, &d.GenerationErrorMessage, &wizardStateJSON, &inputParamsJSON)
|
||||
if err != nil {
|
||||
return nil, response.ErrNotFound(40411, "article_not_found", "article not found")
|
||||
}
|
||||
d.SourceType = dbSourceType
|
||||
if len(wizardStateJSON) > 0 {
|
||||
d.WizardState = map[string]interface{}{}
|
||||
_ = json.Unmarshal(wizardStateJSON, &d.WizardState)
|
||||
}
|
||||
d.GenerationMode = resolveArticleGenerationMode(dbSourceType, inputParamsJSON)
|
||||
d.Platforms = resolveArticlePlatforms(wizardStateJSON, inputParamsJSON)
|
||||
d.WordCount = resolveWordCount(d.MarkdownContent, d.WordCount)
|
||||
return &d, nil
|
||||
@@ -455,6 +475,24 @@ func resolveWordCount(markdown *string, stored int) int {
|
||||
return stored
|
||||
}
|
||||
|
||||
func resolveArticleGenerationMode(sourceType string, inputParamsJSON []byte) *string {
|
||||
if sourceType != "custom_generation" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(inputParamsJSON) > 0 {
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(inputParamsJSON, &payload); err == nil {
|
||||
if mode := strings.TrimSpace(extractString(payload, "generation_mode")); mode != "" {
|
||||
return &mode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mode := "instant"
|
||||
return &mode
|
||||
}
|
||||
|
||||
func nilIfEmptyString(value string) *string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
|
||||
@@ -429,46 +429,6 @@ func (s *BrandService) DeleteQuestion(ctx context.Context, brandID, questionID i
|
||||
return nil
|
||||
}
|
||||
|
||||
type QuestionVersionResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
QuestionID int64 `json:"question_id"`
|
||||
QuestionText string `json:"question_text"`
|
||||
QuestionHash string `json:"question_hash"`
|
||||
VersionNo int `json:"version_no"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func (s *BrandService) ListQuestionVersions(ctx context.Context, brandID int64) ([]QuestionVersionResponse, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT v.id, v.question_id, v.question_text, v.question_hash, v.version_no, v.is_active, v.created_at
|
||||
FROM brand_question_versions v
|
||||
JOIN brand_questions q ON q.id = v.question_id
|
||||
WHERE q.brand_id = $1 AND q.tenant_id = $2
|
||||
ORDER BY v.created_at DESC
|
||||
`, brandID, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to list question versions")
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var versions []QuestionVersionResponse
|
||||
for rows.Next() {
|
||||
var v QuestionVersionResponse
|
||||
var ca interface{}
|
||||
if err := rows.Scan(&v.ID, &v.QuestionID, &v.QuestionText, &v.QuestionHash, &v.VersionNo, &v.IsActive, &ca); err != nil {
|
||||
return nil, response.ErrInternal(50010, "scan_failed", err.Error())
|
||||
}
|
||||
v.CreatedAt = fmt.Sprintf("%v", ca)
|
||||
versions = append(versions, v)
|
||||
}
|
||||
if versions == nil {
|
||||
versions = []QuestionVersionResponse{}
|
||||
}
|
||||
return versions, nil
|
||||
}
|
||||
|
||||
// --- Competitor CRUD ---
|
||||
|
||||
type CompetitorRequest struct {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/geo-platform/tenant-api/internal/shared/auth"
|
||||
"github.com/geo-platform/tenant-api/internal/shared/response"
|
||||
)
|
||||
|
||||
type InstantTaskService struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewInstantTaskService(pool *pgxpool.Pool) *InstantTaskService {
|
||||
return &InstantTaskService{pool: pool}
|
||||
}
|
||||
|
||||
type InstantTaskListParams struct {
|
||||
PromptRuleID *int64
|
||||
Status *string
|
||||
Keyword *string
|
||||
CreatedFrom *time.Time
|
||||
CreatedTo *time.Time
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
type InstantTaskResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
ArticleID *int64 `json:"article_id"`
|
||||
PromptRuleID *int64 `json:"prompt_rule_id"`
|
||||
PromptRuleName *string `json:"prompt_rule_name"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ExecutionTime *string `json:"execution_time"`
|
||||
Platforms []string `json:"platforms"`
|
||||
GenerateCount int `json:"generate_count"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type InstantTaskListResponse struct {
|
||||
Items []InstantTaskResponse `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
func (s *InstantTaskService) List(ctx context.Context, params InstantTaskListParams) (*InstantTaskListResponse, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
if params.Page < 1 {
|
||||
params.Page = 1
|
||||
}
|
||||
if params.PageSize < 1 || params.PageSize > 100 {
|
||||
params.PageSize = 20
|
||||
}
|
||||
offset := (params.Page - 1) * params.PageSize
|
||||
|
||||
var total int64
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM generation_tasks gt
|
||||
LEFT JOIN articles a ON a.id = gt.article_id
|
||||
LEFT JOIN prompt_rules pr ON pr.id = COALESCE(a.prompt_rule_id, NULLIF(gt.input_params_json ->> 'prompt_rule_id', '')::bigint)
|
||||
WHERE gt.tenant_id = $1
|
||||
AND gt.task_type = 'custom_generation'
|
||||
AND ($2::bigint IS NULL OR pr.id = $2)
|
||||
AND ($3::text IS NULL OR gt.status = $3)
|
||||
AND ($4::text IS NULL OR COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '') ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR gt.created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR gt.created_at <= $6)
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo).Scan(&total)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "count_failed", "failed to count instant tasks")
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT gt.id, gt.article_id, pr.id, pr.name,
|
||||
COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '即时任务') AS task_name,
|
||||
gt.status,
|
||||
COALESCE(gt.started_at, gt.completed_at, gt.created_at) AS execution_time,
|
||||
gt.input_params_json,
|
||||
gt.created_at
|
||||
FROM generation_tasks gt
|
||||
LEFT JOIN articles a ON a.id = gt.article_id
|
||||
LEFT JOIN prompt_rules pr ON pr.id = COALESCE(a.prompt_rule_id, NULLIF(gt.input_params_json ->> 'prompt_rule_id', '')::bigint)
|
||||
WHERE gt.tenant_id = $1
|
||||
AND gt.task_type = 'custom_generation'
|
||||
AND ($2::bigint IS NULL OR pr.id = $2)
|
||||
AND ($3::text IS NULL OR gt.status = $3)
|
||||
AND ($4::text IS NULL OR COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '') ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR gt.created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR gt.created_at <= $6)
|
||||
ORDER BY gt.created_at DESC
|
||||
LIMIT $7 OFFSET $8
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo, params.PageSize, offset)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to list instant tasks")
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]InstantTaskResponse, 0)
|
||||
for rows.Next() {
|
||||
var item InstantTaskResponse
|
||||
var executionAt interface{}
|
||||
var createdAt interface{}
|
||||
var inputParamsJSON []byte
|
||||
if err := rows.Scan(
|
||||
&item.ID,
|
||||
&item.ArticleID,
|
||||
&item.PromptRuleID,
|
||||
&item.PromptRuleName,
|
||||
&item.Name,
|
||||
&item.Status,
|
||||
&executionAt,
|
||||
&inputParamsJSON,
|
||||
&createdAt,
|
||||
); err != nil {
|
||||
return nil, response.ErrInternal(50010, "scan_failed", err.Error())
|
||||
}
|
||||
|
||||
item.ExecutionTime = stringPtrFromDBValue(executionAt)
|
||||
item.CreatedAt = fmt.Sprintf("%v", createdAt)
|
||||
item.Platforms = resolveArticlePlatforms(nil, inputParamsJSON)
|
||||
item.GenerateCount = 1
|
||||
|
||||
if len(inputParamsJSON) > 0 {
|
||||
payload, err := parseJSONMap(inputParamsJSON)
|
||||
if err == nil {
|
||||
if count := extractInt(payload, "generate_count"); count > 0 {
|
||||
item.GenerateCount = count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return &InstantTaskListResponse{
|
||||
Items: items,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func stringPtrFromDBValue(value interface{}) *string {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
text := fmt.Sprintf("%v", value)
|
||||
return &text
|
||||
}
|
||||
|
||||
func parseJSONMap(raw []byte) (map[string]interface{}, error) {
|
||||
if len(raw) == 0 {
|
||||
return map[string]interface{}{}, nil
|
||||
}
|
||||
|
||||
payload := make(map[string]interface{})
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
@@ -62,6 +62,8 @@ type promptRuleGenerationRecord struct {
|
||||
Status string
|
||||
}
|
||||
|
||||
const promptRuleGeneratingTitlePlaceholder = "标题生成中"
|
||||
|
||||
func NewPromptRuleGenerationService(
|
||||
pool *pgxpool.Pool,
|
||||
llmClient llm.Client,
|
||||
@@ -121,12 +123,12 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
return nil, response.ErrBadRequest(40018, "generate_count_not_supported", "prompt rule instant generation currently supports generate_count = 1 only")
|
||||
}
|
||||
|
||||
initialTitle := strings.TrimSpace(extractString(extra, "task_name"))
|
||||
if initialTitle == "" {
|
||||
initialTitle = strings.TrimSpace(rule.Name)
|
||||
taskName := strings.TrimSpace(extractString(extra, "task_name"))
|
||||
if taskName == "" {
|
||||
taskName = strings.TrimSpace(rule.Name)
|
||||
}
|
||||
if initialTitle == "" {
|
||||
initialTitle = "Generated Article"
|
||||
if taskName == "" {
|
||||
taskName = "即时任务"
|
||||
}
|
||||
|
||||
quotaRepo := repository.NewQuotaRepository(s.pool)
|
||||
@@ -136,11 +138,14 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
}
|
||||
|
||||
inputParams := map[string]interface{}{
|
||||
"title": initialTitle,
|
||||
"prompt_rule_id": req.PromptRuleID,
|
||||
"task_name": taskName,
|
||||
"target_platform": strings.TrimSpace(derefString(req.TargetPlatform)),
|
||||
"enable_web_search": extractBool(extra, "enable_web_search"),
|
||||
}
|
||||
if generationMode := strings.TrimSpace(extractString(extra, "generation_mode")); generationMode != "" {
|
||||
inputParams["generation_mode"] = generationMode
|
||||
}
|
||||
platformIDs := parsePlatformIDs(derefString(req.TargetPlatform))
|
||||
if len(platformIDs) > 0 {
|
||||
inputParams["target_platforms"] = platformIDs
|
||||
@@ -150,7 +155,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
}
|
||||
|
||||
inputJSON, _ := json.Marshal(inputParams)
|
||||
wizardStateJSON, _ := mergeArticleWizardState(nil, initialTitle, platformIDs)
|
||||
wizardStateJSON, _ := mergeArticleWizardState(nil, promptRuleGeneratingTitlePlaceholder, platformIDs)
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -195,7 +200,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
var articleID int64
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO articles (tenant_id, source_type, prompt_rule_id, generate_status, publish_status, wizard_state_json)
|
||||
VALUES ($1, 'prompt_rule', $2, 'generating', 'unpublished', $3)
|
||||
VALUES ($1, 'custom_generation', $2, 'generating', 'unpublished', $3)
|
||||
RETURNING id
|
||||
`, actor.TenantID, req.PromptRuleID, wizardStateJSON).Scan(&articleID)
|
||||
if err != nil {
|
||||
@@ -211,7 +216,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
TenantID: actor.TenantID,
|
||||
ArticleID: &articleID,
|
||||
QuotaReservationID: &reservationID,
|
||||
TaskType: "prompt_rule",
|
||||
TaskType: "custom_generation",
|
||||
InputParamsJSON: inputJSON,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -230,7 +235,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
ReservationID: reservationID,
|
||||
Prompt: buildPromptRuleGenerationPrompt(rule, inputParams),
|
||||
InputParams: inputParams,
|
||||
InitialTitle: initialTitle,
|
||||
InitialTitle: promptRuleGeneratingTitlePlaceholder,
|
||||
WebSearch: llm.WebSearchOptions{
|
||||
Enabled: extractBool(extra, "enable_web_search"),
|
||||
},
|
||||
@@ -242,7 +247,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
}
|
||||
|
||||
if s.streamEnabled {
|
||||
s.streams.Start(articleID, taskID, initialTitle)
|
||||
s.streams.Start(articleID, taskID, promptRuleGeneratingTitlePlaceholder)
|
||||
}
|
||||
|
||||
return &GenerateFromRuleResponse{ArticleID: articleID, TaskID: taskID}, nil
|
||||
@@ -392,6 +397,10 @@ func (s *PromptRuleGenerationService) executeGeneration(ctx context.Context, job
|
||||
func (s *PromptRuleGenerationService) failGeneration(ctx context.Context, job promptRuleGenerationJob, title, stage string, genErr error) {
|
||||
errMsg := formatGenerationFailure(stage, genErr)
|
||||
now := time.Now()
|
||||
failureTitle := strings.TrimSpace(extractString(job.InputParams, "task_name"))
|
||||
if failureTitle == "" {
|
||||
failureTitle = title
|
||||
}
|
||||
|
||||
auditRepo := repository.NewAuditRepository(s.pool)
|
||||
articleRepo := repository.NewArticleRepository(s.pool)
|
||||
@@ -405,6 +414,14 @@ func (s *PromptRuleGenerationService) failGeneration(ctx context.Context, job pr
|
||||
CompletedAt: &now,
|
||||
})
|
||||
_ = articleRepo.UpdateArticleGenerateStatus(ctx, job.ArticleID, job.TenantID, "failed")
|
||||
if failureTitle != "" {
|
||||
_, _ = s.pool.Exec(ctx, `
|
||||
UPDATE articles
|
||||
SET wizard_state_json = jsonb_set(COALESCE(wizard_state_json, '{}'::jsonb), '{title}', to_jsonb($1::text), true),
|
||||
updated_at = NOW()
|
||||
WHERE id = $2 AND tenant_id = $3
|
||||
`, failureTitle, job.ArticleID, job.TenantID)
|
||||
}
|
||||
|
||||
balance, balanceErr := quotaRepo.GetCurrentBalance(ctx, job.TenantID, "article_generation")
|
||||
if balanceErr == nil {
|
||||
@@ -426,7 +443,7 @@ func (s *PromptRuleGenerationService) failGeneration(ctx context.Context, job pr
|
||||
_ = quotaRepo.RefundReservation(ctx, job.ReservationID, job.TenantID)
|
||||
|
||||
if s.streamEnabled {
|
||||
s.streams.Fail(job.ArticleID, job.TaskID, title, errMsg)
|
||||
s.streams.Fail(job.ArticleID, job.TaskID, failureTitle, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,8 +451,8 @@ func buildPromptRuleGenerationPrompt(rule *promptRuleGenerationRecord, params ma
|
||||
sections := []string{strings.TrimSpace(rule.PromptContent)}
|
||||
|
||||
var supplements []string
|
||||
if title := strings.TrimSpace(extractString(params, "title")); title != "" {
|
||||
supplements = append(supplements, "任务名称:"+title)
|
||||
if taskName := strings.TrimSpace(extractString(params, "task_name")); taskName != "" {
|
||||
supplements = append(supplements, "任务名称:"+taskName)
|
||||
}
|
||||
if rule.Scene != nil && strings.TrimSpace(*rule.Scene) != "" {
|
||||
supplements = append(supplements, "适用场景:"+strings.TrimSpace(*rule.Scene))
|
||||
@@ -454,7 +471,7 @@ func buildPromptRuleGenerationPrompt(rule *promptRuleGenerationRecord, params ma
|
||||
sections = append(sections, "补充要求:\n- "+strings.Join(supplements, "\n- "))
|
||||
}
|
||||
|
||||
sections = append(sections, "输出要求:\n1. 直接输出完整可发布的中文 Markdown 文章。\n2. 标题使用一级标题。\n3. 不要输出你的思考过程、解释或致歉。")
|
||||
sections = append(sections, "输出要求:\n1. 直接输出完整可发布的中文 Markdown 文章。\n2. 标题使用一级标题,并由 AI 根据正文内容自行生成,不要直接复用任务名称。\n3. 不要输出你的思考过程、解释或致歉。")
|
||||
return strings.Join(sections, "\n\n")
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
@@ -52,8 +53,11 @@ type ScheduleTaskResponse struct {
|
||||
type ScheduleTaskListParams struct {
|
||||
PromptRuleID *int64 `json:"prompt_rule_id"`
|
||||
Status *string `json:"status"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Keyword *string `json:"keyword"`
|
||||
CreatedFrom *time.Time
|
||||
CreatedTo *time.Time
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type ScheduleTaskListResponse struct {
|
||||
@@ -81,7 +85,10 @@ func (s *ScheduleTaskService) List(ctx context.Context, params ScheduleTaskListP
|
||||
WHERE tenant_id = $1 AND deleted_at IS NULL
|
||||
AND ($2::bigint IS NULL OR prompt_rule_id = $2)
|
||||
AND ($3::text IS NULL OR status = $3)
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status).Scan(&total)
|
||||
AND ($4::text IS NULL OR name ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR created_at <= $6)
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo).Scan(&total)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "count_failed", "failed to count schedule tasks")
|
||||
}
|
||||
@@ -98,9 +105,12 @@ func (s *ScheduleTaskService) List(ctx context.Context, params ScheduleTaskListP
|
||||
WHERE st.tenant_id = $1 AND st.deleted_at IS NULL
|
||||
AND ($2::bigint IS NULL OR st.prompt_rule_id = $2)
|
||||
AND ($3::text IS NULL OR st.status = $3)
|
||||
AND ($4::text IS NULL OR st.name ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR st.created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR st.created_at <= $6)
|
||||
ORDER BY st.created_at DESC
|
||||
LIMIT $4 OFFSET $5
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.PageSize, offset)
|
||||
LIMIT $7 OFFSET $8
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo, params.PageSize, offset)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to list schedule tasks")
|
||||
}
|
||||
|
||||
@@ -345,47 +345,6 @@ func (q *Queries) ListKeywords(ctx context.Context, arg ListKeywordsParams) ([]L
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listQuestionVersions = `-- name: ListQuestionVersions :many
|
||||
SELECT v.id, v.question_id, v.question_text, v.question_hash, v.version_no, v.is_active, v.created_at
|
||||
FROM brand_question_versions v
|
||||
JOIN brand_questions q ON q.id = v.question_id
|
||||
WHERE q.brand_id = $1 AND q.tenant_id = $2
|
||||
ORDER BY v.created_at DESC
|
||||
`
|
||||
|
||||
type ListQuestionVersionsParams struct {
|
||||
BrandID int64 `json:"brand_id"`
|
||||
TenantID int64 `json:"tenant_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) ListQuestionVersions(ctx context.Context, arg ListQuestionVersionsParams) ([]BrandQuestionVersion, error) {
|
||||
rows, err := q.db.Query(ctx, listQuestionVersions, arg.BrandID, arg.TenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []BrandQuestionVersion
|
||||
for rows.Next() {
|
||||
var i BrandQuestionVersion
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.QuestionID,
|
||||
&i.QuestionText,
|
||||
&i.QuestionHash,
|
||||
&i.VersionNo,
|
||||
&i.IsActive,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listQuestions = `-- name: ListQuestions :many
|
||||
SELECT q.id, q.tenant_id, q.brand_id, q.keyword_id, q.current_version_id, q.status, q.created_at,
|
||||
v.question_text, v.version_no
|
||||
|
||||
@@ -79,6 +79,7 @@ type Brand struct {
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
DeletedAt pgtype.Timestamptz `json:"deleted_at"`
|
||||
Website pgtype.Text `json:"website"`
|
||||
}
|
||||
|
||||
type BrandKeyword struct {
|
||||
|
||||
@@ -61,7 +61,6 @@ type Querier interface {
|
||||
// ============================================================
|
||||
ListPromptRules(ctx context.Context, arg ListPromptRulesParams) ([]ListPromptRulesRow, error)
|
||||
ListPromptRulesUngrouped(ctx context.Context, arg ListPromptRulesUngroupedParams) ([]ListPromptRulesUngroupedRow, error)
|
||||
ListQuestionVersions(ctx context.Context, arg ListQuestionVersionsParams) ([]BrandQuestionVersion, error)
|
||||
ListQuestions(ctx context.Context, arg ListQuestionsParams) ([]ListQuestionsRow, error)
|
||||
ListScheduleTasks(ctx context.Context, arg ListScheduleTasksParams) ([]ListScheduleTasksRow, error)
|
||||
ListTemplates(ctx context.Context, tenantID int64) ([]ListTemplatesRow, error)
|
||||
|
||||
@@ -85,13 +85,6 @@ WHERE id = sqlc.arg(id) AND brand_id = sqlc.arg(brand_id) AND tenant_id = sqlc.a
|
||||
UPDATE brand_questions SET deleted_at = NOW(), updated_at = NOW()
|
||||
WHERE brand_id = sqlc.arg(brand_id) AND tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;
|
||||
|
||||
-- name: ListQuestionVersions :many
|
||||
SELECT v.id, v.question_id, v.question_text, v.question_hash, v.version_no, v.is_active, v.created_at
|
||||
FROM brand_question_versions v
|
||||
JOIN brand_questions q ON q.id = v.question_id
|
||||
WHERE q.brand_id = sqlc.arg(brand_id) AND q.tenant_id = sqlc.arg(tenant_id)
|
||||
ORDER BY v.created_at DESC;
|
||||
|
||||
-- name: ListCompetitors :many
|
||||
SELECT id, tenant_id, brand_id, name, website, description, product_lines_json, created_at, updated_at
|
||||
FROM competitors
|
||||
|
||||
@@ -50,6 +50,9 @@ func (h *ArticleHandler) List(c *gin.Context) {
|
||||
if v := c.Query("source_type"); v != "" {
|
||||
params.SourceType = &v
|
||||
}
|
||||
if v := c.Query("generation_mode"); v != "" {
|
||||
params.GenerationMode = &v
|
||||
}
|
||||
if v := c.Query("template_id"); v != "" {
|
||||
if id, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
params.TemplateID = &id
|
||||
|
||||
@@ -202,16 +202,6 @@ func (h *BrandHandler) DeleteQuestion(c *gin.Context) {
|
||||
response.Success(c, nil)
|
||||
}
|
||||
|
||||
func (h *BrandHandler) ListQuestionVersions(c *gin.Context) {
|
||||
brandID, _ := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
data, err := h.svc.ListQuestionVersions(c.Request.Context(), brandID)
|
||||
if err != nil {
|
||||
response.Error(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, data)
|
||||
}
|
||||
|
||||
// Competitors
|
||||
func (h *BrandHandler) ListCompetitors(c *gin.Context) {
|
||||
brandID, _ := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/geo-platform/tenant-api/internal/bootstrap"
|
||||
"github.com/geo-platform/tenant-api/internal/shared/response"
|
||||
"github.com/geo-platform/tenant-api/internal/tenant/app"
|
||||
)
|
||||
|
||||
type InstantTaskHandler struct {
|
||||
svc *app.InstantTaskService
|
||||
}
|
||||
|
||||
func NewInstantTaskHandler(a *bootstrap.App) *InstantTaskHandler {
|
||||
return &InstantTaskHandler{svc: app.NewInstantTaskService(a.DB)}
|
||||
}
|
||||
|
||||
func (h *InstantTaskHandler) List(c *gin.Context) {
|
||||
params := app.InstantTaskListParams{
|
||||
Page: 1,
|
||||
PageSize: 20,
|
||||
}
|
||||
if v := c.Query("page"); v != "" {
|
||||
if p, err := strconv.Atoi(v); err == nil {
|
||||
params.Page = p
|
||||
}
|
||||
}
|
||||
if v := c.Query("page_size"); v != "" {
|
||||
if ps, err := strconv.Atoi(v); err == nil {
|
||||
params.PageSize = ps
|
||||
}
|
||||
}
|
||||
if v := c.Query("prompt_rule_id"); v != "" {
|
||||
if rid, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
params.PromptRuleID = &rid
|
||||
}
|
||||
}
|
||||
if v := c.Query("status"); v != "" {
|
||||
params.Status = &v
|
||||
}
|
||||
if v := c.Query("keyword"); v != "" {
|
||||
params.Keyword = &v
|
||||
}
|
||||
if v := c.Query("created_from"); v != "" {
|
||||
parsed, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
response.Error(c, response.ErrBadRequest(40014, "invalid_created_from", "created_from must be RFC3339"))
|
||||
return
|
||||
}
|
||||
params.CreatedFrom = &parsed
|
||||
}
|
||||
if v := c.Query("created_to"); v != "" {
|
||||
parsed, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
response.Error(c, response.ErrBadRequest(40015, "invalid_created_to", "created_to must be RFC3339"))
|
||||
return
|
||||
}
|
||||
params.CreatedTo = &parsed
|
||||
}
|
||||
|
||||
data, err := h.svc.List(c.Request.Context(), params)
|
||||
if err != nil {
|
||||
response.Error(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, data)
|
||||
}
|
||||
@@ -64,7 +64,6 @@ func RegisterRoutes(app *bootstrap.App) {
|
||||
brands.POST("/:id/questions", brandHandler.CreateQuestion)
|
||||
brands.PUT("/:id/questions/:qid", brandHandler.UpdateQuestion)
|
||||
brands.DELETE("/:id/questions/:qid", brandHandler.DeleteQuestion)
|
||||
brands.GET("/:id/question-versions", brandHandler.ListQuestionVersions)
|
||||
brands.GET("/:id/competitors", brandHandler.ListCompetitors)
|
||||
brands.POST("/:id/competitors", brandHandler.CreateCompetitor)
|
||||
brands.PUT("/:id/competitors/:cid", brandHandler.UpdateCompetitor)
|
||||
@@ -95,4 +94,8 @@ func RegisterRoutes(app *bootstrap.App) {
|
||||
schedules.PUT("/:id", schHandler.Update)
|
||||
schedules.DELETE("/:id", schHandler.Delete)
|
||||
schedules.PUT("/:id/status", schHandler.ToggleStatus)
|
||||
|
||||
instantTasks := protected.Group("/tenant/instant-tasks")
|
||||
instHandler := NewInstantTaskHandler(app)
|
||||
instantTasks.GET("", instHandler.List)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package transport
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -41,6 +42,25 @@ func (h *ScheduleTaskHandler) List(c *gin.Context) {
|
||||
if v := c.Query("status"); v != "" {
|
||||
params.Status = &v
|
||||
}
|
||||
if v := c.Query("keyword"); v != "" {
|
||||
params.Keyword = &v
|
||||
}
|
||||
if v := c.Query("created_from"); v != "" {
|
||||
parsed, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
response.Error(c, response.ErrBadRequest(40014, "invalid_created_from", "created_from must be RFC3339"))
|
||||
return
|
||||
}
|
||||
params.CreatedFrom = &parsed
|
||||
}
|
||||
if v := c.Query("created_to"); v != "" {
|
||||
parsed, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
response.Error(c, response.ErrBadRequest(40015, "invalid_created_to", "created_to must be RFC3339"))
|
||||
return
|
||||
}
|
||||
params.CreatedTo = &parsed
|
||||
}
|
||||
|
||||
data, err := h.svc.List(c.Request.Context(), params)
|
||||
if err != nil {
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
UPDATE articles
|
||||
SET source_type = 'prompt_rule'
|
||||
WHERE source_type = 'custom_generation';
|
||||
|
||||
UPDATE generation_tasks
|
||||
SET task_type = 'prompt_rule'
|
||||
WHERE task_type = 'custom_generation';
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
UPDATE articles
|
||||
SET source_type = 'custom_generation'
|
||||
WHERE source_type = 'prompt_rule';
|
||||
|
||||
UPDATE generation_tasks
|
||||
SET task_type = 'custom_generation'
|
||||
WHERE task_type = 'prompt_rule';
|
||||
Reference in New Issue
Block a user