feat: add brand library management features

- Introduced BrandLibrarySummary type to encapsulate brand library limits and usage.
- Updated Brand interface to include keyword_count and question_count fields.
- Implemented brand library limits in the backend, including max brands, keywords, and questions per keyword.
- Added API endpoint to retrieve brand library summary.
- Enhanced BrandsView.vue to display brand library usage and limits.
- Implemented computed properties to manage brand, keyword, and question limits in the UI.
- Updated mutation handlers to invalidate relevant queries upon creating/updating brands, keywords, and questions.
- Added visual indicators for brand, keyword, and question limits in the UI.
- Enhanced error handling for exceeding brand and keyword limits during creation.
This commit is contained in:
2026-04-16 21:01:40 +08:00
parent 27389164b0
commit 41f3060e00
15 changed files with 731 additions and 44 deletions
+6
View File
@@ -59,6 +59,12 @@ monitoring_workers:
result_ingest_concurrency: 4
projection_rebuild_concurrency: 2
brand_library:
free_brand_limit: 1
paid_brand_limit: 2
max_keywords: 5
max_questions_per_keyword: 5
redis:
addr: localhost:6379
+6
View File
@@ -63,6 +63,12 @@ monitoring_workers:
result_ingest_concurrency: 4
projection_rebuild_concurrency: 2
brand_library:
free_brand_limit: 1
paid_brand_limit: 2
max_keywords: 5
max_questions_per_keyword: 5
redis:
addr: localhost:6379
db: 0
+35
View File
@@ -16,6 +16,7 @@ type Config struct {
RabbitMQ RabbitMQConfig `mapstructure:"rabbitmq"`
Scheduler SchedulerConfig `mapstructure:"scheduler"`
MonitoringWorkers MonitoringConfig `mapstructure:"monitoring_workers"`
BrandLibrary BrandLibraryConfig `mapstructure:"brand_library"`
Redis RedisConfig `mapstructure:"redis"`
Qdrant QdrantConfig `mapstructure:"qdrant"`
ObjectStorage ObjectStorageConfig `mapstructure:"object_storage"`
@@ -103,6 +104,20 @@ type MonitoringConfig struct {
ProjectionRebuildConcurrency int `mapstructure:"projection_rebuild_concurrency"`
}
type BrandLibraryConfig struct {
FreeBrandLimit int `mapstructure:"free_brand_limit"`
PaidBrandLimit int `mapstructure:"paid_brand_limit"`
MaxKeywords int `mapstructure:"max_keywords"`
MaxQuestionsPerKeyword int `mapstructure:"max_questions_per_keyword"`
}
func (c BrandLibraryConfig) BrandLimitForPlan(planCode string) int {
if strings.EqualFold(strings.TrimSpace(planCode), "free") {
return c.FreeBrandLimit
}
return c.PaidBrandLimit
}
type QdrantConfig struct {
URL string `mapstructure:"url"`
APIKey string `mapstructure:"api_key"`
@@ -196,6 +211,7 @@ func Load(configPath string) (*Config, error) {
normalizeRabbitMQConfig(&cfg.RabbitMQ)
normalizeSchedulerConfig(&cfg.Scheduler)
normalizeMonitoringConfig(&cfg.MonitoringWorkers)
normalizeBrandLibraryConfig(&cfg.BrandLibrary)
return &cfg, nil
}
@@ -398,6 +414,25 @@ func normalizeMonitoringConfig(cfg *MonitoringConfig) {
}
}
func normalizeBrandLibraryConfig(cfg *BrandLibraryConfig) {
if cfg == nil {
return
}
if cfg.FreeBrandLimit <= 0 {
cfg.FreeBrandLimit = 1
}
if cfg.PaidBrandLimit <= 0 {
cfg.PaidBrandLimit = 2
}
if cfg.MaxKeywords <= 0 {
cfg.MaxKeywords = 5
}
if cfg.MaxQuestionsPerKeyword <= 0 {
cfg.MaxQuestionsPerKeyword = 5
}
}
func lookupFirstNonEmptyEnv(keys ...string) (string, bool) {
for _, key := range keys {
if value, ok := lookupNonEmptyEnv(key); ok {
@@ -89,6 +89,30 @@ retrieval:
}
}
func TestLoadAppliesBrandLibraryDefaults(t *testing.T) {
configPath := writeTestConfig(t, `
brand_library: {}
`)
cfg, err := Load(configPath)
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if cfg.BrandLibrary.FreeBrandLimit != 1 {
t.Fatalf("expected default free brand limit 1, got %d", cfg.BrandLibrary.FreeBrandLimit)
}
if cfg.BrandLibrary.PaidBrandLimit != 2 {
t.Fatalf("expected default paid brand limit 2, got %d", cfg.BrandLibrary.PaidBrandLimit)
}
if cfg.BrandLibrary.MaxKeywords != 5 {
t.Fatalf("expected default max keywords 5, got %d", cfg.BrandLibrary.MaxKeywords)
}
if cfg.BrandLibrary.MaxQuestionsPerKeyword != 5 {
t.Fatalf("expected default max questions per keyword 5, got %d", cfg.BrandLibrary.MaxQuestionsPerKeyword)
}
}
func writeTestConfig(t *testing.T, body string) string {
t.Helper()
+332 -34
View File
@@ -8,12 +8,14 @@ import (
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/sync/singleflight"
"github.com/geo-platform/tenant-api/internal/shared/auditlog"
"github.com/geo-platform/tenant-api/internal/shared/auth"
sharedcache "github.com/geo-platform/tenant-api/internal/shared/cache"
sharedconfig "github.com/geo-platform/tenant-api/internal/shared/config"
"github.com/geo-platform/tenant-api/internal/shared/middleware"
"github.com/geo-platform/tenant-api/internal/shared/response"
)
@@ -21,13 +23,14 @@ import (
type BrandService struct {
pool *pgxpool.Pool
monitoringPool *pgxpool.Pool
limits sharedconfig.BrandLibraryConfig
auditLogs *auditlog.AsyncWriter
cache sharedcache.Cache
cacheGroup singleflight.Group
}
func NewBrandService(pool, monitoringPool *pgxpool.Pool, auditLogs *auditlog.AsyncWriter) *BrandService {
return &BrandService{pool: pool, monitoringPool: monitoringPool, auditLogs: auditLogs}
func NewBrandService(pool, monitoringPool *pgxpool.Pool, auditLogs *auditlog.AsyncWriter, limits sharedconfig.BrandLibraryConfig) *BrandService {
return &BrandService{pool: pool, monitoringPool: monitoringPool, limits: limits, auditLogs: auditLogs}
}
func (s *BrandService) WithCache(c sharedcache.Cache) *BrandService {
@@ -44,13 +47,27 @@ type BrandRequest struct {
}
type BrandResponse struct {
ID int64 `json:"id"`
Name string `json:"name"`
Website *string `json:"website"`
Description *string `json:"description"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ID int64 `json:"id"`
Name string `json:"name"`
Website *string `json:"website"`
Description *string `json:"description"`
Status string `json:"status"`
KeywordCount int `json:"keyword_count"`
QuestionCount int `json:"question_count"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type BrandLibrarySummaryResponse struct {
PlanCode string `json:"plan_code"`
PlanName string `json:"plan_name"`
MaxBrands int `json:"max_brands"`
UsedBrands int `json:"used_brands"`
RemainingBrands int `json:"remaining_brands"`
MaxKeywords int `json:"max_keywords"`
UsedKeywords int `json:"used_keywords"`
RemainingKeywords int `json:"remaining_keywords"`
MaxQuestionsPerKeyword int `json:"max_questions_per_keyword"`
}
func (s *BrandService) List(ctx context.Context) ([]BrandResponse, error) {
@@ -60,20 +77,47 @@ func (s *BrandService) List(ctx context.Context) ([]BrandResponse, error) {
})
}
func (s *BrandService) Summary(ctx context.Context) (*BrandLibrarySummaryResponse, error) {
actor := auth.MustActor(ctx)
return sharedcache.LoadJSON(ctx, s.cache, &s.cacheGroup, brandLibrarySummaryCacheKey(actor.TenantID), defaultCacheTTL(), func(loadCtx context.Context) (*BrandLibrarySummaryResponse, error) {
return s.loadBrandLibrarySummary(loadCtx, actor.TenantID)
})
}
func (s *BrandService) Create(ctx context.Context, req BrandRequest) (*BrandResponse, error) {
actor := auth.MustActor(ctx)
normalizeBrandRequest(&req)
if req.Name == "" {
return nil, response.ErrBadRequest(40001, "invalid_params", "name is required")
}
summary, err := s.loadBrandLibrarySummary(ctx, actor.TenantID)
if err != nil {
return nil, err
}
var id int64
var ca interface{}
err := s.pool.QueryRow(ctx, `
err = s.pool.QueryRow(ctx, `
WITH usage AS (
SELECT COUNT(*)::INT AS used_brands
FROM brands
WHERE tenant_id = $1 AND deleted_at IS NULL
)
INSERT INTO brands (tenant_id, name, website, description, status)
VALUES ($1, $2, $3, $4, 'active') RETURNING id, created_at
`, actor.TenantID, req.Name, req.Website, req.Description).Scan(&id, &ca)
SELECT $1, $2, $3, $4, 'active'
FROM usage
WHERE usage.used_brands < $5
RETURNING id, created_at
`, actor.TenantID, req.Name, req.Website, req.Description, summary.MaxBrands).Scan(&id, &ca)
if err != nil {
return nil, response.ErrConflict(40901, "brand_exists", "brand with this name already exists")
if errors.Is(err, pgx.ErrNoRows) {
return nil, response.ErrConflict(40904, "brand_limit_reached", fmt.Sprintf("current plan allows up to %d brand companies", summary.MaxBrands))
}
if isUniqueConstraintError(err, "uk_brand_tenant_name_active") {
return nil, response.ErrConflict(40901, "brand_exists", "brand with this name already exists")
}
return nil, response.ErrInternal(50010, "create_failed", "failed to create brand")
}
afterJSON, _ := json.Marshal(map[string]interface{}{"id": id, "name": req.Name})
@@ -94,12 +138,14 @@ func (s *BrandService) Create(ctx context.Context, req BrandRequest) (*BrandResp
invalidateBrandCaches(ctx, s.cache, actor.TenantID, id)
return &BrandResponse{
ID: id,
Name: req.Name,
Website: req.Website,
Description: req.Description,
Status: "active",
CreatedAt: fmt.Sprintf("%v", ca),
ID: id,
Name: req.Name,
Website: req.Website,
Description: req.Description,
Status: "active",
KeywordCount: 0,
QuestionCount: 0,
CreatedAt: fmt.Sprintf("%v", ca),
}, nil
}
@@ -127,7 +173,13 @@ func (s *BrandService) Update(ctx context.Context, id int64, req BrandRequest) e
UPDATE brands SET name = $1, website = $2, description = $3, updated_at = NOW()
WHERE id = $4 AND tenant_id = $5 AND deleted_at IS NULL
`, req.Name, req.Website, req.Description, id, actor.TenantID)
if err != nil || tag.RowsAffected() == 0 {
if err != nil {
if isUniqueConstraintError(err, "uk_brand_tenant_name_active") {
return response.ErrConflict(40901, "brand_exists", "brand with this name already exists")
}
return response.ErrInternal(50010, "update_failed", "failed to update brand")
}
if tag.RowsAffected() == 0 {
return response.ErrNotFound(40420, "brand_not_found", "brand not found")
}
invalidateBrandCaches(ctx, s.cache, actor.TenantID, id)
@@ -216,13 +268,48 @@ func (s *BrandService) ListKeywords(ctx context.Context, brandID int64) ([]Keywo
func (s *BrandService) CreateKeyword(ctx context.Context, brandID int64, req KeywordRequest) (*KeywordResponse, error) {
actor := auth.MustActor(ctx)
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
return nil, response.ErrBadRequest(40001, "invalid_params", "name is required")
}
exists, err := s.brandExists(ctx, actor.TenantID, brandID)
if err != nil {
return nil, err
}
if !exists {
return nil, response.ErrNotFound(40420, "brand_not_found", "brand not found")
}
summary, err := s.loadBrandLibrarySummary(ctx, actor.TenantID)
if err != nil {
return nil, err
}
var id int64
var ca interface{}
err := s.pool.QueryRow(ctx, `
INSERT INTO brand_keywords (tenant_id, brand_id, name, status) VALUES ($1, $2, $3, 'active') RETURNING id, created_at
`, actor.TenantID, brandID, req.Name).Scan(&id, &ca)
err = s.pool.QueryRow(ctx, `
WITH usage AS (
SELECT COUNT(*)::INT AS used_keywords
FROM brand_keywords
WHERE tenant_id = $1 AND deleted_at IS NULL
)
INSERT INTO brand_keywords (tenant_id, brand_id, name, status)
SELECT $1, $2, $3, 'active'
FROM usage
WHERE usage.used_keywords < $4
RETURNING id, created_at
`, actor.TenantID, brandID, req.Name, summary.MaxKeywords).Scan(&id, &ca)
if err != nil {
return nil, response.ErrConflict(40902, "keyword_exists", "keyword with this name already exists for this brand")
if errors.Is(err, pgx.ErrNoRows) {
return nil, response.ErrConflict(40905, "keyword_limit_reached", fmt.Sprintf("current plan allows up to %d keywords", summary.MaxKeywords))
}
if isUniqueConstraintError(err, "uk_brand_keyword_name_active") {
return nil, response.ErrConflict(40902, "keyword_exists", "keyword with this name already exists for this brand")
}
if isForeignKeyConstraintError(err) {
return nil, response.ErrNotFound(40420, "brand_not_found", "brand not found")
}
return nil, response.ErrInternal(50010, "create_failed", "failed to create keyword")
}
invalidateBrandCaches(ctx, s.cache, actor.TenantID, brandID)
return &KeywordResponse{ID: id, BrandID: brandID, Name: req.Name, Status: "active", CreatedAt: fmt.Sprintf("%v", ca)}, nil
@@ -230,11 +317,21 @@ func (s *BrandService) CreateKeyword(ctx context.Context, brandID int64, req Key
func (s *BrandService) UpdateKeyword(ctx context.Context, brandID, keywordID int64, req KeywordRequest) error {
actor := auth.MustActor(ctx)
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
return response.ErrBadRequest(40001, "invalid_params", "name is required")
}
tag, err := s.pool.Exec(ctx, `
UPDATE brand_keywords SET name = $1, updated_at = NOW()
WHERE id = $2 AND brand_id = $3 AND tenant_id = $4 AND deleted_at IS NULL
`, req.Name, keywordID, brandID, actor.TenantID)
if err != nil || tag.RowsAffected() == 0 {
if err != nil {
if isUniqueConstraintError(err, "uk_brand_keyword_name_active") {
return response.ErrConflict(40902, "keyword_exists", "keyword with this name already exists for this brand")
}
return response.ErrInternal(50010, "update_failed", "failed to update keyword")
}
if tag.RowsAffected() == 0 {
return response.ErrNotFound(40421, "keyword_not_found", "keyword not found")
}
invalidateBrandCaches(ctx, s.cache, actor.TenantID, brandID)
@@ -331,19 +428,48 @@ func (s *BrandService) ListQuestions(ctx context.Context, brandID int64, keyword
func (s *BrandService) CreateQuestion(ctx context.Context, brandID int64, req QuestionRequest) (*QuestionResponse, error) {
actor := auth.MustActor(ctx)
if req.KeywordID <= 0 {
return nil, response.ErrBadRequest(40001, "invalid_params", "keyword_id is required")
}
req.QuestionText = strings.TrimSpace(req.QuestionText)
if req.QuestionText == "" {
return nil, response.ErrBadRequest(40001, "invalid_params", "question_text is required")
}
exists, err := s.keywordExistsForBrand(ctx, actor.TenantID, brandID, req.KeywordID)
if err != nil {
return nil, err
}
if !exists {
return nil, response.ErrNotFound(40421, "keyword_not_found", "keyword not found")
}
summary, err := s.loadBrandLibrarySummary(ctx, actor.TenantID)
if err != nil {
return nil, err
}
var questionID int64
var ca interface{}
err := s.pool.QueryRow(ctx, `
err = s.pool.QueryRow(ctx, `
WITH usage AS (
SELECT COUNT(*)::INT AS used_questions
FROM brand_questions
WHERE tenant_id = $1 AND keyword_id = $3 AND deleted_at IS NULL
)
INSERT INTO brand_questions (tenant_id, brand_id, keyword_id, question_text, status)
VALUES ($1, $2, $3, $4, 'active')
SELECT $1, $2, $3, $4, 'active'
FROM usage
WHERE usage.used_questions < $5
RETURNING id, created_at
`, actor.TenantID, brandID, req.KeywordID, req.QuestionText).Scan(&questionID, &ca)
`, actor.TenantID, brandID, req.KeywordID, req.QuestionText, summary.MaxQuestionsPerKeyword).Scan(&questionID, &ca)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, response.ErrConflict(40906, "question_limit_reached", fmt.Sprintf("each keyword allows up to %d questions", summary.MaxQuestionsPerKeyword))
}
if isForeignKeyConstraintError(err) {
return nil, response.ErrNotFound(40421, "keyword_not_found", "keyword not found")
}
return nil, response.ErrInternal(50010, "create_failed", "failed to create question")
}
@@ -488,8 +614,32 @@ func (s *BrandService) DeleteCompetitor(ctx context.Context, brandID, competitor
func (s *BrandService) loadBrands(ctx context.Context, tenantID int64) ([]BrandResponse, error) {
rows, err := s.pool.Query(ctx, `
SELECT id, name, website, description, status, created_at, updated_at
FROM brands WHERE tenant_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC
SELECT
b.id,
b.name,
b.website,
b.description,
b.status,
COALESCE(stats.keyword_count, 0) AS keyword_count,
COALESCE(stats.question_count, 0) AS question_count,
b.created_at,
b.updated_at
FROM brands b
LEFT JOIN LATERAL (
SELECT
COUNT(DISTINCT k.id)::INT AS keyword_count,
COUNT(q.id)::INT AS question_count
FROM brand_keywords k
LEFT JOIN brand_questions q
ON q.keyword_id = k.id
AND q.tenant_id = b.tenant_id
AND q.deleted_at IS NULL
WHERE k.brand_id = b.id
AND k.tenant_id = b.tenant_id
AND k.deleted_at IS NULL
) stats ON true
WHERE b.tenant_id = $1 AND b.deleted_at IS NULL
ORDER BY b.created_at DESC
`, tenantID)
if err != nil {
return nil, response.ErrInternal(50010, "query_failed", "failed to list brands")
@@ -501,7 +651,7 @@ func (s *BrandService) loadBrands(ctx context.Context, tenantID int64) ([]BrandR
var item BrandResponse
var createdAt interface{}
var updatedAt interface{}
if err := rows.Scan(&item.ID, &item.Name, &item.Website, &item.Description, &item.Status, &createdAt, &updatedAt); err != nil {
if err := rows.Scan(&item.ID, &item.Name, &item.Website, &item.Description, &item.Status, &item.KeywordCount, &item.QuestionCount, &createdAt, &updatedAt); err != nil {
return nil, response.ErrInternal(50010, "scan_failed", err.Error())
}
item.CreatedAt = fmt.Sprintf("%v", createdAt)
@@ -516,9 +666,32 @@ func (s *BrandService) loadBrandDetail(ctx context.Context, tenantID, brandID in
var createdAt interface{}
var updatedAt interface{}
err := s.pool.QueryRow(ctx, `
SELECT id, name, website, description, status, created_at, updated_at
FROM brands WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL
`, brandID, tenantID).Scan(&item.ID, &item.Name, &item.Website, &item.Description, &item.Status, &createdAt, &updatedAt)
SELECT
b.id,
b.name,
b.website,
b.description,
b.status,
COALESCE(stats.keyword_count, 0) AS keyword_count,
COALESCE(stats.question_count, 0) AS question_count,
b.created_at,
b.updated_at
FROM brands b
LEFT JOIN LATERAL (
SELECT
COUNT(DISTINCT k.id)::INT AS keyword_count,
COUNT(q.id)::INT AS question_count
FROM brand_keywords k
LEFT JOIN brand_questions q
ON q.keyword_id = k.id
AND q.tenant_id = b.tenant_id
AND q.deleted_at IS NULL
WHERE k.brand_id = b.id
AND k.tenant_id = b.tenant_id
AND k.deleted_at IS NULL
) stats ON true
WHERE b.id = $1 AND b.tenant_id = $2 AND b.deleted_at IS NULL
`, brandID, tenantID).Scan(&item.ID, &item.Name, &item.Website, &item.Description, &item.Status, &item.KeywordCount, &item.QuestionCount, &createdAt, &updatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, false, nil
@@ -612,3 +785,128 @@ func (s *BrandService) loadBrandCompetitors(ctx context.Context, tenantID, brand
}
return items, nil
}
type brandLibraryPlan struct {
PlanCode string
PlanName string
}
type brandLibraryUsage struct {
BrandCount int
KeywordCount int
}
func (s *BrandService) loadBrandLibrarySummary(ctx context.Context, tenantID int64) (*BrandLibrarySummaryResponse, error) {
plan, err := s.loadBrandLibraryPlan(ctx, tenantID)
if err != nil {
return nil, err
}
usage, err := s.loadBrandLibraryUsage(ctx, tenantID)
if err != nil {
return nil, err
}
maxBrands := s.limits.BrandLimitForPlan(plan.PlanCode)
maxKeywords := s.limits.MaxKeywords
return &BrandLibrarySummaryResponse{
PlanCode: plan.PlanCode,
PlanName: plan.PlanName,
MaxBrands: maxBrands,
UsedBrands: usage.BrandCount,
RemainingBrands: maxInt(maxBrands-usage.BrandCount, 0),
MaxKeywords: maxKeywords,
UsedKeywords: usage.KeywordCount,
RemainingKeywords: maxInt(maxKeywords-usage.KeywordCount, 0),
MaxQuestionsPerKeyword: s.limits.MaxQuestionsPerKeyword,
}, nil
}
func (s *BrandService) loadBrandLibraryPlan(ctx context.Context, tenantID int64) (*brandLibraryPlan, error) {
plan := &brandLibraryPlan{
PlanCode: "free",
PlanName: "",
}
err := s.pool.QueryRow(ctx, `
SELECT p.plan_code, p.name
FROM tenant_plan_subscriptions s
JOIN plans p ON p.id = s.plan_id
WHERE s.tenant_id = $1
AND s.status = 'active'
AND s.deleted_at IS NULL
ORDER BY s.start_at DESC
LIMIT 1
`, tenantID).Scan(&plan.PlanCode, &plan.PlanName)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return plan, nil
}
return nil, response.ErrInternal(50010, "query_failed", "failed to load active plan")
}
return plan, nil
}
func (s *BrandService) loadBrandLibraryUsage(ctx context.Context, tenantID int64) (*brandLibraryUsage, error) {
usage := &brandLibraryUsage{}
err := s.pool.QueryRow(ctx, `
SELECT
(SELECT COUNT(*)::INT FROM brands WHERE tenant_id = $1 AND deleted_at IS NULL) AS brand_count,
(SELECT COUNT(*)::INT FROM brand_keywords WHERE tenant_id = $1 AND deleted_at IS NULL) AS keyword_count
`, tenantID).Scan(&usage.BrandCount, &usage.KeywordCount)
if err != nil {
return nil, response.ErrInternal(50010, "query_failed", "failed to load brand library usage")
}
return usage, nil
}
func (s *BrandService) brandExists(ctx context.Context, tenantID, brandID int64) (bool, error) {
var exists bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1
FROM brands
WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL
)
`, brandID, tenantID).Scan(&exists)
if err != nil {
return false, response.ErrInternal(50010, "query_failed", "failed to load brand")
}
return exists, nil
}
func (s *BrandService) keywordExistsForBrand(ctx context.Context, tenantID, brandID, keywordID int64) (bool, error) {
var exists bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1
FROM brand_keywords
WHERE id = $1
AND brand_id = $2
AND tenant_id = $3
AND deleted_at IS NULL
)
`, keywordID, brandID, tenantID).Scan(&exists)
if err != nil {
return false, response.ErrInternal(50010, "query_failed", "failed to load keyword")
}
return exists, nil
}
func isUniqueConstraintError(err error, constraint string) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
}
func isForeignKeyConstraintError(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
func maxInt(value, floor int) int {
if value < floor {
return floor
}
return value
}
@@ -75,6 +75,10 @@ func brandListCacheKey(tenantID int64) string {
return fmt.Sprintf("brand:list:%d", tenantID)
}
func brandLibrarySummaryCacheKey(tenantID int64) string {
return fmt.Sprintf("brand:library_summary:%d", tenantID)
}
func brandDetailCacheKey(tenantID, brandID int64) string {
return fmt.Sprintf("brand:detail:%d:%d", tenantID, brandID)
}
@@ -121,6 +125,7 @@ func invalidateBrandCaches(ctx context.Context, c sharedcache.Cache, tenantID, b
deleteCachePrefix(ctx, c, brandQuestionsCachePrefix(tenantID, brandID))
deleteCachePrefix(ctx, c, brandCompetitorsCachePrefix(tenantID, brandID))
deleteCacheKey(ctx, c, brandListCacheKey(tenantID))
deleteCacheKey(ctx, c, brandLibrarySummaryCacheKey(tenantID))
deleteCachePrefix(ctx, c, scheduleTaskListCachePrefix(tenantID))
deleteCachePrefix(ctx, c, scheduleTaskDetailCachePrefix(tenantID))
invalidateWorkspaceCaches(ctx, c, tenantID)
@@ -15,7 +15,7 @@ type BrandHandler struct {
}
func NewBrandHandler(a *bootstrap.App) *BrandHandler {
return &BrandHandler{svc: app.NewBrandService(a.DB, a.MonitoringDB, a.AuditLogs).WithCache(a.Cache)}
return &BrandHandler{svc: app.NewBrandService(a.DB, a.MonitoringDB, a.AuditLogs, a.Config.BrandLibrary).WithCache(a.Cache)}
}
func (h *BrandHandler) List(c *gin.Context) {
@@ -27,6 +27,15 @@ func (h *BrandHandler) List(c *gin.Context) {
response.Success(c, data)
}
func (h *BrandHandler) Summary(c *gin.Context) {
data, err := h.svc.Summary(c.Request.Context())
if err != nil {
response.Error(c, err)
return
}
response.Success(c, data)
}
func (h *BrandHandler) Create(c *gin.Context) {
var req app.BrandRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -80,6 +80,7 @@ func RegisterRoutes(app *bootstrap.App) {
brands := protected.Group("/tenant/brands")
brandHandler := NewBrandHandler(app)
brands.GET("", brandHandler.List)
brands.GET("/library-summary", brandHandler.Summary)
brands.POST("", brandHandler.Create)
brands.GET("/:id", brandHandler.Detail)
brands.PUT("/:id", brandHandler.Update)
@@ -29,6 +29,7 @@ func TestProtectedRoutes_RequireAuth(t *testing.T) {
{http.MethodGet, "/api/tenant/templates"},
{http.MethodGet, "/api/tenant/articles"},
{http.MethodGet, "/api/tenant/brands"},
{http.MethodGet, "/api/tenant/brands/library-summary"},
{http.MethodGet, "/api/tenant/monitoring/brands/:brand_id/questions/:question_id/detail"},
{http.MethodPost, "/api/tenant/brands"},
}