|
|
|
@@ -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
|
|
|
|
|
}
|
|
|
|
|