mirror of
https://github.com/won-ktds/smarketing-backend.git
synced 2026-01-21 19:16:23 +00:00
Merge pull request #6 from won-ktds/ai-recommend
feat: ai-recommend 마케팅 팁 생성
This commit is contained in:
commit
aeab66ec39
131
smarketing-ai/api/marketing_tip_api.py
Normal file
131
smarketing-ai/api/marketing_tip_api.py
Normal file
@ -0,0 +1,131 @@
|
||||
"""
|
||||
마케팅 팁 생성 API 엔드포인트
|
||||
Java 서비스와 연동되는 API
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
from services.marketing_tip_service import MarketingTipService
|
||||
from models.marketing_tip_models import MarketingTipGenerateRequest, MarketingTipResponse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Blueprint 생성
|
||||
marketing_tip_bp = Blueprint('marketing_tip', __name__)
|
||||
|
||||
# 서비스 인스턴스
|
||||
marketing_tip_service = MarketingTipService()
|
||||
|
||||
|
||||
@marketing_tip_bp.route('/api/v1/generate-marketing-tip', methods=['POST'])
|
||||
def generate_marketing_tip():
|
||||
"""
|
||||
AI 마케팅 팁 생성 API
|
||||
Java 서비스에서 호출하는 엔드포인트
|
||||
"""
|
||||
try:
|
||||
# 요청 데이터 검증
|
||||
if not request.is_json:
|
||||
return jsonify({
|
||||
'tip': '',
|
||||
'status': 'error',
|
||||
'message': 'Content-Type이 application/json이어야 합니다.',
|
||||
'generated_at': '',
|
||||
'store_name': '',
|
||||
'business_type': '',
|
||||
'ai_model': ''
|
||||
}), 400
|
||||
|
||||
data = request.get_json()
|
||||
if not data:
|
||||
return jsonify({
|
||||
'tip': '',
|
||||
'status': 'error',
|
||||
'message': '요청 데이터가 없습니다.',
|
||||
'generated_at': '',
|
||||
'store_name': '',
|
||||
'business_type': '',
|
||||
'ai_model': ''
|
||||
}), 400
|
||||
|
||||
# 필수 필드 검증
|
||||
if 'store_name' not in data or not data['store_name']:
|
||||
return jsonify({
|
||||
'tip': '',
|
||||
'status': 'error',
|
||||
'message': '매장명(store_name)은 필수입니다.',
|
||||
'generated_at': '',
|
||||
'store_name': '',
|
||||
'business_type': '',
|
||||
'ai_model': ''
|
||||
}), 400
|
||||
|
||||
if 'business_type' not in data or not data['business_type']:
|
||||
return jsonify({
|
||||
'tip': '',
|
||||
'status': 'error',
|
||||
'message': '업종(business_type)은 필수입니다.',
|
||||
'generated_at': '',
|
||||
'store_name': '',
|
||||
'business_type': '',
|
||||
'ai_model': ''
|
||||
}), 400
|
||||
|
||||
logger.info(f"마케팅 팁 생성 요청: {data.get('store_name', 'Unknown')}")
|
||||
|
||||
# 요청 모델 생성
|
||||
try:
|
||||
request_model = MarketingTipGenerateRequest(**data)
|
||||
except ValueError as e:
|
||||
return jsonify({
|
||||
'tip': '',
|
||||
'status': 'error',
|
||||
'message': f'요청 데이터 형식이 올바르지 않습니다: {str(e)}',
|
||||
'generated_at': '',
|
||||
'store_name': data.get('store_name', ''),
|
||||
'business_type': data.get('business_type', ''),
|
||||
'ai_model': ''
|
||||
}), 400
|
||||
|
||||
# 매장 정보 구성
|
||||
store_data = {
|
||||
'store_name': request_model.store_name,
|
||||
'business_type': request_model.business_type,
|
||||
'location': request_model.location or '',
|
||||
'seat_count': request_model.seat_count or 0
|
||||
}
|
||||
|
||||
# 마케팅 팁 생성
|
||||
result = marketing_tip_service.generate_marketing_tip(
|
||||
store_data=store_data,
|
||||
)
|
||||
|
||||
logger.info(f"마케팅 팁 생성 완료: {result.get('store_name', 'Unknown')}")
|
||||
|
||||
return jsonify(result), 200
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"마케팅 팁 생성 API 오류: {str(e)}")
|
||||
|
||||
return jsonify({
|
||||
'tip': '죄송합니다. 일시적인 오류로 마케팅 팁을 생성할 수 없습니다. 잠시 후 다시 시도해주세요.',
|
||||
'status': 'error',
|
||||
'message': f'서버 오류가 발생했습니다: {str(e)}',
|
||||
'generated_at': '',
|
||||
'store_name': data.get('store_name', '') if 'data' in locals() else '',
|
||||
'business_type': data.get('business_type', '') if 'data' in locals() else '',
|
||||
'ai_model': 'error'
|
||||
}), 500
|
||||
|
||||
|
||||
@marketing_tip_bp.route('/api/v1/health', methods=['GET'])
|
||||
def health_check():
|
||||
"""
|
||||
헬스체크 API
|
||||
"""
|
||||
return jsonify({
|
||||
'status': 'healthy',
|
||||
'service': 'marketing-tip-api',
|
||||
'timestamp': datetime.now().isoformat()
|
||||
}), 200
|
||||
@ -33,6 +33,9 @@ def create_app():
|
||||
poster_service_v3 = PosterServiceV3()
|
||||
sns_content_service = SnsContentService()
|
||||
|
||||
# Blueprint 등록
|
||||
app.register_blueprint(marketing_tip_bp)
|
||||
|
||||
@app.route('/health', methods=['GET'])
|
||||
def health_check():
|
||||
"""헬스 체크 API"""
|
||||
|
||||
93
smarketing-ai/models/marketing_tip_models.py
Normal file
93
smarketing-ai/models/marketing_tip_models.py
Normal file
@ -0,0 +1,93 @@
|
||||
"""
|
||||
마케팅 팁 API 요청/응답 모델
|
||||
"""
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class MenuInfo(BaseModel):
|
||||
"""메뉴 정보 모델"""
|
||||
|
||||
menu_id: int = Field(..., description="메뉴 ID")
|
||||
menu_name: str = Field(..., description="메뉴명")
|
||||
category: str = Field(..., description="메뉴 카테고리")
|
||||
price: int = Field(..., description="가격")
|
||||
description: Optional[str] = Field(None, description="메뉴 설명")
|
||||
|
||||
class Config:
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"store_name": "더블샷 카페",
|
||||
"business_type": "카페",
|
||||
"location": "서울시 강남구 역삼동",
|
||||
"seat_count": 30,
|
||||
"menu_list": [
|
||||
{
|
||||
"menu_id": 1,
|
||||
"menu_name": "아메리카노",
|
||||
"category": "음료",
|
||||
"price": 4000,
|
||||
"description": "깊고 진한 맛의 아메리카노"
|
||||
},
|
||||
{
|
||||
"menu_id": 2,
|
||||
"menu_name": "카페라떼",
|
||||
"category": "음료",
|
||||
"price": 4500,
|
||||
"description": "부드러운 우유 거품이 올라간 카페라떼"
|
||||
},
|
||||
{
|
||||
"menu_id": 3,
|
||||
"menu_name": "치즈케이크",
|
||||
"category": "디저트",
|
||||
"price": 6000,
|
||||
"description": "진한 치즈 맛의 수제 케이크"
|
||||
}
|
||||
],
|
||||
"additional_requirement": "젊은 고객층을 타겟으로 한 마케팅"
|
||||
}
|
||||
}
|
||||
|
||||
class MarketingTipGenerateRequest(BaseModel):
|
||||
"""마케팅 팁 생성 요청 모델"""
|
||||
|
||||
store_name: str = Field(..., description="매장명")
|
||||
business_type: str = Field(..., description="업종")
|
||||
location: Optional[str] = Field(None, description="위치")
|
||||
seat_count: Optional[int] = Field(None, description="좌석 수")
|
||||
menu_list: Optional[List[MenuInfo]] = Field(default=[], description="메뉴 목록")
|
||||
|
||||
class Config:
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"store_name": "더블샷 카페",
|
||||
"business_type": "카페",
|
||||
"location": "서울시 강남구 역삼동",
|
||||
"seat_count": 30,
|
||||
}
|
||||
}
|
||||
|
||||
class MarketingTipResponse(BaseModel):
|
||||
"""마케팅 팁 응답 모델"""
|
||||
|
||||
tip: str = Field(..., description="생성된 마케팅 팁")
|
||||
status: str = Field(..., description="응답 상태 (success, fallback, error)")
|
||||
message: str = Field(..., description="응답 메시지")
|
||||
generated_at: str = Field(..., description="생성 시간")
|
||||
store_name: str = Field(..., description="매장명")
|
||||
business_type: str = Field(..., description="업종")
|
||||
ai_model: str = Field(..., description="사용된 AI 모델")
|
||||
|
||||
class Config:
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"tip": "☕ 더블샷 카페 여름 마케팅 전략\n\n💡 핵심 포인트:\n1. 여름 한정 시원한 음료 개발\n2. SNS 이벤트로 젊은 고객층 공략\n3. 더위 피할 수 있는 쾌적한 환경 어필",
|
||||
"status": "success",
|
||||
"message": "AI 마케팅 팁이 성공적으로 생성되었습니다.",
|
||||
"generated_at": "2024-06-13T15:30:00",
|
||||
"store_name": "더블샷 카페",
|
||||
"business_type": "카페",
|
||||
"ai_model": "claude"
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,6 @@ API 요청 데이터 구조를 정의
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
from datetime import date
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
331
smarketing-ai/services/marketing_tip_service.py
Normal file
331
smarketing-ai/services/marketing_tip_service.py
Normal file
@ -0,0 +1,331 @@
|
||||
"""
|
||||
마케팅 팁 생성 서비스
|
||||
Java 서비스에서 요청받은 매장 정보를 기반으로 AI 마케팅 팁을 생성
|
||||
"""
|
||||
import os
|
||||
import logging
|
||||
from typing import Dict, Any, Optional
|
||||
import anthropic
|
||||
import openai
|
||||
from datetime import datetime
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MarketingTipService:
|
||||
"""마케팅 팁 생성 서비스 클래스"""
|
||||
|
||||
def __init__(self):
|
||||
"""서비스 초기화"""
|
||||
self.claude_api_key = os.getenv('CLAUDE_API_KEY')
|
||||
self.openai_api_key = os.getenv('OPENAI_API_KEY')
|
||||
|
||||
# Claude 클라이언트 초기화
|
||||
if self.claude_api_key:
|
||||
self.claude_client = anthropic.Anthropic(api_key=self.claude_api_key)
|
||||
else:
|
||||
self.claude_client = None
|
||||
logger.warning("Claude API 키가 설정되지 않았습니다.")
|
||||
|
||||
# OpenAI 클라이언트 초기화
|
||||
if self.openai_api_key:
|
||||
self.openai_client = openai.OpenAI(api_key=self.openai_api_key)
|
||||
else:
|
||||
self.openai_client = None
|
||||
logger.warning("OpenAI API 키가 설정되지 않았습니다.")
|
||||
|
||||
def generate_marketing_tip(self, store_data: Dict[str, Any], additional_requirement: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
매장 정보를 기반으로 AI 마케팅 팁 생성
|
||||
|
||||
Args:
|
||||
store_data: 매장 정보 (store_name, business_type, location 등)
|
||||
|
||||
Returns:
|
||||
생성된 마케팅 팁과 메타데이터
|
||||
"""
|
||||
try:
|
||||
logger.info(f"마케팅 팁 생성 시작: {store_data.get('store_name', 'Unknown')}")
|
||||
|
||||
# 1. 프롬프트 생성
|
||||
prompt = self._create_marketing_prompt(store_data, additional_requirement)
|
||||
|
||||
# 2. AI 서비스 호출 (Claude 우선, 실패 시 OpenAI)
|
||||
tip_content = self._call_ai_service(prompt)
|
||||
|
||||
# 3. 응답 데이터 구성
|
||||
response = {
|
||||
'tip': tip_content,
|
||||
'status': 'success',
|
||||
'message': 'AI 마케팅 팁이 성공적으로 생성되었습니다.',
|
||||
'generated_at': datetime.now().isoformat(),
|
||||
'store_name': store_data.get('store_name', ''),
|
||||
'business_type': store_data.get('business_type', ''),
|
||||
'ai_model': 'claude' if self.claude_client else 'openai'
|
||||
}
|
||||
|
||||
logger.info(f"마케팅 팁 생성 완료: {store_data.get('store_name', 'Unknown')}")
|
||||
logger.info(f"마케팅 팁 생성 완료: {response}")
|
||||
return response
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"마케팅 팁 생성 실패: {str(e)}")
|
||||
|
||||
# 실패 시 Fallback 팁 반환
|
||||
fallback_tip = self._create_fallback_tip(store_data, additional_requirement)
|
||||
|
||||
return {
|
||||
'tip': fallback_tip,
|
||||
'status': 'fallback',
|
||||
'message': 'AI 서비스 호출 실패로 기본 팁을 제공합니다.',
|
||||
'generated_at': datetime.now().isoformat(),
|
||||
'store_name': store_data.get('store_name', ''),
|
||||
'business_type': store_data.get('business_type', ''),
|
||||
'ai_model': 'fallback'
|
||||
}
|
||||
|
||||
def _create_marketing_prompt(self, store_data: Dict[str, Any], additional_requirement: Optional[str]) -> str:
|
||||
"""마케팅 팁 생성을 위한 프롬프트 생성"""
|
||||
|
||||
store_name = store_data.get('store_name', '매장')
|
||||
business_type = store_data.get('business_type', '소상공인')
|
||||
location = store_data.get('location', '')
|
||||
seat_count = store_data.get('seat_count', 0)
|
||||
menu_list = store_data.get('menu_list', [])
|
||||
|
||||
prompt = f"""
|
||||
당신은 소상공인 마케팅 전문가입니다.
|
||||
현재 유행하고 성공한 마케팅 예시를 검색하여 확인 한 후, 참고하여 아래 내용을 작성해주세요.
|
||||
|
||||
당신의 임무는 매장 정보를 바탕으로, 적은 비용으로 효과를 낼 수 있는 현실적이고 실행 가능한 마케팅 팁을 제안하는 것입니다.
|
||||
지역성, 지역의 현재 날씨 확인하고, 현재 트렌드까지 고려해주세요.
|
||||
소상공인을 위한 실용적인 마케팅 팁을 생성해주세요.
|
||||
|
||||
매장 정보:
|
||||
- 매장명: {store_name}
|
||||
- 업종: {business_type}
|
||||
- 위치: {location}
|
||||
- 좌석 수: {seat_count}석
|
||||
|
||||
"""
|
||||
# 🔥 메뉴 정보 추가
|
||||
if menu_list and len(menu_list) > 0:
|
||||
prompt += f"\n메뉴 정보:\n"
|
||||
for menu in menu_list:
|
||||
menu_name = menu.get('menu_name', '')
|
||||
category = menu.get('category', '')
|
||||
price = menu.get('price', 0)
|
||||
description = menu.get('description', '')
|
||||
prompt += f"- {menu_name} ({category}): {price:,}원 - {description}\n"
|
||||
|
||||
prompt += """
|
||||
아래 조건을 모두 충족하는 마케팅 팁을 하나 생성해주세요:
|
||||
|
||||
1. **실행 가능성**: 소상공인이 실제로 적용할 수 있는 현실적인 방법
|
||||
2. **비용 효율성**: 적은 비용으로 높은 효과를 기대할 수 있는 전략
|
||||
3. **구체성**: 실행 단계가 명확하고 구체적일 것
|
||||
4. **시의성**: 현재 계절, 유행, 트렌드를 반영
|
||||
5. **지역성**: 지역 특성 및 현재 날씨를 고려할 것
|
||||
|
||||
응답 형식 (300자 내외, 간결하게):
|
||||
html 형식으로 출력
|
||||
핵심 마케팅 팁은 제목없이 한번 더 상단에 보여주세요
|
||||
부제목과 내용은 분리해서 출력
|
||||
아래의 부제목 앞에는 이모지 포함
|
||||
- 핵심 마케팅 팁 (1개)
|
||||
- 실행 방법 (1개)
|
||||
- 예상 비용과 기대 효과
|
||||
- 주의사항 또는 유의점
|
||||
- 참고했던 실제 성공한 마케팅
|
||||
- 오늘의 응원의 문장 (간결하게 1개)
|
||||
|
||||
심호흡하고, 단계별로 차근차근 생각해서 정확하고 실현 가능한 아이디어를 제시해주세요.
|
||||
"""
|
||||
|
||||
return prompt
|
||||
|
||||
def _call_ai_service(self, prompt: str) -> str:
|
||||
"""AI 서비스 호출"""
|
||||
|
||||
# Claude API 우선 시도
|
||||
if self.claude_client:
|
||||
try:
|
||||
response = self.claude_client.messages.create(
|
||||
model="claude-3-sonnet-20240229",
|
||||
max_tokens=1000,
|
||||
temperature=0.7,
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
if response.content and len(response.content) > 0:
|
||||
logger.info(f"마케팅 팁 생성 완료: {response.content}")
|
||||
return response.content[0].text.strip()
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Claude API 호출 실패: {str(e)}")
|
||||
|
||||
# OpenAI API 시도
|
||||
if self.openai_client:
|
||||
try:
|
||||
response = self.openai_client.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
"content": "당신은 소상공인을 위한 마케팅 전문가입니다. 실용적이고 구체적인 마케팅 조언을 제공해주세요."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}
|
||||
],
|
||||
max_tokens=800,
|
||||
temperature=0.7
|
||||
)
|
||||
|
||||
if response.choices and len(response.choices) > 0:
|
||||
return response.choices[0].message.content.strip()
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"OpenAI API 호출 실패: {str(e)}")
|
||||
|
||||
# 모든 AI 서비스 호출 실패
|
||||
raise Exception("모든 AI 서비스 호출에 실패했습니다.")
|
||||
|
||||
def _create_fallback_tip(self, store_data: Dict[str, Any], additional_requirement: Optional[str]) -> str:
|
||||
"""AI 서비스 실패 시 규칙 기반 Fallback 팁 생성"""
|
||||
|
||||
store_name = store_data.get('store_name', '매장')
|
||||
business_type = store_data.get('business_type', '')
|
||||
location = store_data.get('location', '')
|
||||
menu_list = store_data.get('menu_list', [])
|
||||
|
||||
if menu_list and len(menu_list) > 0:
|
||||
# 가장 비싼 메뉴 찾기 (시그니처 메뉴로 가정)
|
||||
expensive_menu = max(menu_list, key=lambda x: x.get('price', 0), default=None)
|
||||
|
||||
# 카테고리별 메뉴 분석
|
||||
categories = {}
|
||||
for menu in menu_list:
|
||||
category = menu.get('category', '기타')
|
||||
if category not in categories:
|
||||
categories[category] = []
|
||||
categories[category].append(menu)
|
||||
|
||||
main_category = max(categories.keys(), key=lambda x: len(categories[x])) if categories else '메뉴'
|
||||
|
||||
if expensive_menu:
|
||||
signature_menu = expensive_menu.get('menu_name', '시그니처 메뉴')
|
||||
return f"""🎯 {store_name} 메뉴 기반 마케팅 전략
|
||||
|
||||
💡 핵심 전략:
|
||||
- SNS를 활용한 홍보 강화
|
||||
- 고객 리뷰 관리 및 적극 활용
|
||||
- 지역 커뮤니티 참여로 인지도 향상
|
||||
|
||||
📱 실행 방법:
|
||||
1. 인스타그램/네이버 블로그 정기 포스팅
|
||||
2. 고객 만족도 조사 및 피드백 반영
|
||||
3. 주변 상권과의 협력 이벤트 기획
|
||||
|
||||
💰 예상 효과: 월 매출 10-15% 증가 가능
|
||||
⚠️ 주의사항: 꾸준한 실행과 고객 소통이 핵심"""
|
||||
|
||||
# 업종별 기본 팁
|
||||
if '카페' in business_type or '커피' in business_type:
|
||||
return f"""☕ {store_name} 카페 마케팅 전략
|
||||
|
||||
💡 핵심 포인트:
|
||||
1. 시그니처 음료 개발 및 SNS 홍보
|
||||
2. 계절별 한정 메뉴로 재방문 유도
|
||||
3. 인스타그램 포토존 설치
|
||||
|
||||
📱 실행 방법:
|
||||
- 매주 신메뉴 또는 이벤트 인스타 포스팅
|
||||
- 고객 사진 리포스트로 참여 유도
|
||||
- 해시태그 #근처카페 #데이트코스 활용
|
||||
|
||||
💰 비용: 월 5-10만원 내외
|
||||
📈 기대효과: 젊은 고객층 20% 증가"""
|
||||
|
||||
elif '음식점' in business_type or '식당' in business_type:
|
||||
return f"""🍽️ {store_name} 음식점 마케팅 전략
|
||||
|
||||
💡 핵심 포인트:
|
||||
1. 대표 메뉴 스토리텔링
|
||||
2. 배달앱 리뷰 관리 강화
|
||||
3. 단골 고객 혜택 프로그램
|
||||
|
||||
📱 실행 방법:
|
||||
- 요리 과정 영상으로 신뢰도 구축
|
||||
- 리뷰 적극 답변으로 고객 관리
|
||||
- 방문 횟수별 할인 혜택 제공
|
||||
|
||||
💰 비용: 월 3-7만원 내외
|
||||
📈 기대효과: 재방문율 25% 향상"""
|
||||
|
||||
elif '베이커리' in business_type or '빵집' in business_type:
|
||||
return f"""🍞 {store_name} 베이커리 마케팅 전략
|
||||
|
||||
💡 핵심 포인트:
|
||||
1. 갓 구운 빵 타이밍 알림 서비스
|
||||
2. 계절 한정 빵 출시
|
||||
3. 포장 디자인으로 선물용 어필
|
||||
|
||||
📱 실행 방법:
|
||||
- 네이버 톡톡으로 빵 완성 시간 안내
|
||||
- 명절/기념일 특별 빵 한정 판매
|
||||
- 예쁜 포장지로 브랜딩 강화
|
||||
|
||||
💰 비용: 월 5-8만원 내외
|
||||
📈 기대효과: 단골 고객 30% 증가"""
|
||||
|
||||
# 지역별 특성 고려
|
||||
if location:
|
||||
location_tip = ""
|
||||
if '강남' in location or '서초' in location:
|
||||
location_tip = "\n🏢 강남권 특화: 직장인 대상 점심 세트메뉴 강화"
|
||||
elif '홍대' in location or '신촌' in location:
|
||||
location_tip = "\n🎓 대학가 특화: 학생 할인 및 그룹 이벤트 진행"
|
||||
elif '강북' in location or '노원' in location:
|
||||
location_tip = "\n🏘️ 주거지역 특화: 가족 단위 고객 대상 패키지 상품"
|
||||
|
||||
return f"""🎯 {store_name} 지역 맞춤 마케팅
|
||||
|
||||
💡 기본 전략:
|
||||
- 온라인 리뷰 관리 강화
|
||||
- 단골 고객 혜택 프로그램
|
||||
- 지역 커뮤니티 참여{location_tip}
|
||||
|
||||
📱 실행 방법:
|
||||
1. 구글/네이버 지도 정보 최신화
|
||||
2. 동네 맘카페 홍보 참여
|
||||
3. 주변 상권과 상생 이벤트
|
||||
|
||||
💰 비용: 월 3-5만원
|
||||
📈 기대효과: 인지도 및 매출 향상"""
|
||||
|
||||
# 기본 범용 팁
|
||||
return f"""🎯 {store_name} 기본 마케팅 전략
|
||||
|
||||
💡 핵심 3가지:
|
||||
1. 온라인 존재감 강화 (SNS, 리뷰 관리)
|
||||
2. 고객 소통 및 피드백 활용
|
||||
3. 차별화된 서비스 제공
|
||||
|
||||
📱 실행 방법:
|
||||
- 네이버 플레이스, 구글 정보 최신화
|
||||
- 고객 불만 신속 해결로 신뢰 구축
|
||||
- 작은 이벤트라도 꾸준히 진행
|
||||
|
||||
💰 비용: 거의 무료 (시간 투자 위주)
|
||||
📈 기대효과: 꾸준한 성장과 단골 확보
|
||||
|
||||
⚠️ 핵심은 지속성입니다!"""
|
||||
42
smarketing-ai/test.py
Normal file
42
smarketing-ai/test.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""
|
||||
마케팅 팁 API 테스트 스크립트
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
|
||||
|
||||
def test_marketing_tip_api():
|
||||
"""마케팅 팁 API 테스트"""
|
||||
|
||||
# 테스트 데이터
|
||||
test_data = {
|
||||
"store_name": "더블샷 카페",
|
||||
"business_type": "카페",
|
||||
"location": "서울시 강남구 역삼동",
|
||||
"seat_count": 30,
|
||||
}
|
||||
|
||||
# API 호출
|
||||
url = "http://localhost:5001/api/v1/generate-marketing-tip"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer dummy-key"
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=test_data, headers=headers)
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
print(f"Response: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
||||
|
||||
if response.status_code == 200:
|
||||
print("✅ 테스트 성공!")
|
||||
else:
|
||||
print("❌ 테스트 실패!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 테스트 오류: {str(e)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_marketing_tip_api()
|
||||
@ -4,23 +4,26 @@ import com.won.smarketing.common.exception.BusinessException;
|
||||
import com.won.smarketing.common.exception.ErrorCode;
|
||||
import com.won.smarketing.recommend.application.usecase.MarketingTipUseCase;
|
||||
import com.won.smarketing.recommend.domain.model.MarketingTip;
|
||||
import com.won.smarketing.recommend.domain.model.MenuData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreWithMenuData;
|
||||
import com.won.smarketing.recommend.domain.repository.MarketingTipRepository;
|
||||
import com.won.smarketing.recommend.domain.service.StoreDataProvider;
|
||||
import com.won.smarketing.recommend.domain.service.AiTipGenerator;
|
||||
import com.won.smarketing.recommend.presentation.dto.MarketingTipRequest;
|
||||
import com.won.smarketing.recommend.domain.service.StoreDataProvider;
|
||||
import com.won.smarketing.recommend.presentation.dto.MarketingTipResponse;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* 마케팅 팁 서비스 구현체
|
||||
*/
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@ -32,70 +35,134 @@ public class MarketingTipService implements MarketingTipUseCase {
|
||||
private final AiTipGenerator aiTipGenerator;
|
||||
|
||||
@Override
|
||||
public MarketingTipResponse generateMarketingTips(MarketingTipRequest request) {
|
||||
log.info("마케팅 팁 생성 시작: storeId={}", request.getStoreId());
|
||||
|
||||
public MarketingTipResponse provideMarketingTip() {
|
||||
String userId = getCurrentUserId();
|
||||
log.info("마케팅 팁 제공: userId={}", userId);
|
||||
|
||||
try {
|
||||
// 1. 매장 정보 조회
|
||||
StoreData storeData = storeDataProvider.getStoreData(request.getStoreId());
|
||||
log.debug("매장 정보 조회 완료: {}", storeData.getStoreName());
|
||||
|
||||
// 2. Python AI 서비스로 팁 생성 (매장 정보 + 추가 요청사항 전달)
|
||||
String aiGeneratedTip = aiTipGenerator.generateTip(storeData, request.getAdditionalRequirement());
|
||||
log.debug("AI 팁 생성 완료: {}", aiGeneratedTip.substring(0, Math.min(50, aiGeneratedTip.length())));
|
||||
|
||||
// 3. 도메인 객체 생성 및 저장
|
||||
MarketingTip marketingTip = MarketingTip.builder()
|
||||
.storeId(request.getStoreId())
|
||||
.tipContent(aiGeneratedTip)
|
||||
.storeData(storeData)
|
||||
.build();
|
||||
|
||||
MarketingTip savedTip = marketingTipRepository.save(marketingTip);
|
||||
log.info("마케팅 팁 저장 완료: tipId={}", savedTip.getId().getValue());
|
||||
|
||||
return convertToResponse(savedTip);
|
||||
|
||||
// 1. 사용자의 매장 정보 조회
|
||||
StoreWithMenuData storeWithMenuData = storeDataProvider.getStoreWithMenuData(userId);
|
||||
|
||||
// 2. 1시간 이내에 생성된 마케팅 팁이 있는지 DB에서 확인
|
||||
Optional<MarketingTip> recentTip = findRecentMarketingTip(storeWithMenuData.getStoreData().getStoreId());
|
||||
|
||||
if (recentTip.isPresent()) {
|
||||
log.info("1시간 이내에 생성된 마케팅 팁 발견: tipId={}", recentTip.get().getId().getValue());
|
||||
log.info("1시간 이내에 생성된 마케팅 팁 발견: getTipContent()={}", recentTip.get().getTipContent());
|
||||
return convertToResponse(recentTip.get(), storeWithMenuData.getStoreData(), true);
|
||||
}
|
||||
|
||||
// 3. 1시간 이내 팁이 없으면 새로 생성
|
||||
log.info("1시간 이내 마케팅 팁이 없어 새로 생성합니다: userId={}, storeId={}", userId, storeWithMenuData.getStoreData().getStoreId());
|
||||
MarketingTip newTip = createNewMarketingTip(storeWithMenuData);
|
||||
return convertToResponse(newTip, storeWithMenuData.getStoreData(), false);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("마케팅 팁 생성 중 오류: storeId={}", request.getStoreId(), e);
|
||||
log.error("마케팅 팁 조회/생성 중 오류: userId={}", userId, e);
|
||||
throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
@Cacheable(value = "marketingTipHistory", key = "#storeId + '_' + #pageable.pageNumber + '_' + #pageable.pageSize")
|
||||
public Page<MarketingTipResponse> getMarketingTipHistory(Long storeId, Pageable pageable) {
|
||||
log.info("마케팅 팁 이력 조회: storeId={}", storeId);
|
||||
|
||||
Page<MarketingTip> tips = marketingTipRepository.findByStoreIdOrderByCreatedAtDesc(storeId, pageable);
|
||||
|
||||
return tips.map(this::convertToResponse);
|
||||
/**
|
||||
* DB에서 1시간 이내 생성된 마케팅 팁 조회
|
||||
*/
|
||||
private Optional<MarketingTip> findRecentMarketingTip(Long storeId) {
|
||||
log.debug("DB에서 1시간 이내 마케팅 팁 조회: storeId={}", storeId);
|
||||
|
||||
// 최근 생성된 팁 1개 조회
|
||||
Pageable pageable = PageRequest.of(0, 1);
|
||||
Page<MarketingTip> recentTips = marketingTipRepository.findByStoreIdOrderByCreatedAtDesc(storeId, pageable);
|
||||
|
||||
if (recentTips.isEmpty()) {
|
||||
log.debug("매장의 마케팅 팁이 존재하지 않음: storeId={}", storeId);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
MarketingTip mostRecentTip = recentTips.getContent().get(0);
|
||||
LocalDateTime oneHourAgo = LocalDateTime.now().minusHours(1);
|
||||
|
||||
// 1시간 이내에 생성된 팁인지 확인
|
||||
if (mostRecentTip.getCreatedAt().isAfter(oneHourAgo)) {
|
||||
log.debug("1시간 이내 마케팅 팁 발견: tipId={}, 생성시간={}",
|
||||
mostRecentTip.getId().getValue(), mostRecentTip.getCreatedAt());
|
||||
return Optional.of(mostRecentTip);
|
||||
}
|
||||
|
||||
log.debug("가장 최근 팁이 1시간 이전에 생성됨: tipId={}, 생성시간={}",
|
||||
mostRecentTip.getId().getValue(), mostRecentTip.getCreatedAt());
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public MarketingTipResponse getMarketingTip(Long tipId) {
|
||||
log.info("마케팅 팁 상세 조회: tipId={}", tipId);
|
||||
|
||||
MarketingTip marketingTip = marketingTipRepository.findById(tipId)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR));
|
||||
|
||||
return convertToResponse(marketingTip);
|
||||
/**
|
||||
* 새로운 마케팅 팁 생성
|
||||
*/
|
||||
private MarketingTip createNewMarketingTip(StoreWithMenuData storeWithMenuData) {
|
||||
log.info("새로운 마케팅 팁 생성 시작: storeName={}", storeWithMenuData.getStoreData().getStoreName());
|
||||
|
||||
// AI 서비스로 팁 생성
|
||||
String aiGeneratedTip = aiTipGenerator.generateTip(storeWithMenuData);
|
||||
log.debug("AI 팁 생성 완료: {}", aiGeneratedTip.substring(0, Math.min(50, aiGeneratedTip.length())));
|
||||
|
||||
// 도메인 객체 생성 및 저장
|
||||
MarketingTip marketingTip = MarketingTip.builder()
|
||||
.storeId(storeWithMenuData.getStoreData().getStoreId())
|
||||
.tipContent(aiGeneratedTip)
|
||||
.storeWithMenuData(storeWithMenuData)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.build();
|
||||
|
||||
MarketingTip savedTip = marketingTipRepository.save(marketingTip);
|
||||
log.info("새로운 마케팅 팁 저장 완료: tipId={}", savedTip.getId().getValue());
|
||||
log.info("새로운 마케팅 팁 저장 완료: savedTip.getTipContent()={}", savedTip.getTipContent());
|
||||
|
||||
return savedTip;
|
||||
}
|
||||
|
||||
private MarketingTipResponse convertToResponse(MarketingTip marketingTip) {
|
||||
/**
|
||||
* 마케팅 팁을 응답 DTO로 변환 (전체 내용 포함)
|
||||
*/
|
||||
private MarketingTipResponse convertToResponse(MarketingTip marketingTip, StoreData storeData, boolean isRecentlyCreated) {
|
||||
String tipSummary = generateTipSummary(marketingTip.getTipContent());
|
||||
|
||||
return MarketingTipResponse.builder()
|
||||
.tipId(marketingTip.getId().getValue())
|
||||
.storeId(marketingTip.getStoreId())
|
||||
.storeName(marketingTip.getStoreData().getStoreName())
|
||||
.tipContent(marketingTip.getTipContent())
|
||||
.tipSummary(tipSummary)
|
||||
.tipContent(marketingTip.getTipContent()) // 🆕 전체 내용 포함
|
||||
.storeInfo(MarketingTipResponse.StoreInfo.builder()
|
||||
.storeName(marketingTip.getStoreData().getStoreName())
|
||||
.businessType(marketingTip.getStoreData().getBusinessType())
|
||||
.location(marketingTip.getStoreData().getLocation())
|
||||
.storeName(storeData.getStoreName())
|
||||
.businessType(storeData.getBusinessType())
|
||||
.location(storeData.getLocation())
|
||||
.build())
|
||||
.createdAt(marketingTip.getCreatedAt())
|
||||
.updatedAt(marketingTip.getUpdatedAt())
|
||||
.isRecentlyCreated(isRecentlyCreated)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 마케팅 팁 요약 생성 (첫 50자 또는 첫 번째 문장)
|
||||
*/
|
||||
private String generateTipSummary(String fullContent) {
|
||||
if (fullContent == null || fullContent.trim().isEmpty()) {
|
||||
return "마케팅 팁이 생성되었습니다.";
|
||||
}
|
||||
|
||||
// 첫 번째 문장으로 요약 (마침표 기준)
|
||||
String[] sentences = fullContent.split("[.!?]");
|
||||
String firstSentence = sentences.length > 0 ? sentences[0].trim() : fullContent;
|
||||
|
||||
// 50자 제한
|
||||
if (firstSentence.length() > 50) {
|
||||
return firstSentence.substring(0, 47) + "...";
|
||||
}
|
||||
|
||||
return firstSentence;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 로그인된 사용자 ID 조회
|
||||
*/
|
||||
private String getCurrentUserId() {
|
||||
return SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
}
|
||||
}
|
||||
@ -1,27 +1,12 @@
|
||||
package com.won.smarketing.recommend.application.usecase;
|
||||
|
||||
import com.won.smarketing.recommend.presentation.dto.MarketingTipRequest;
|
||||
import com.won.smarketing.recommend.presentation.dto.MarketingTipResponse;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
/**
|
||||
* 마케팅 팁 유즈케이스 인터페이스
|
||||
*/
|
||||
public interface MarketingTipUseCase {
|
||||
|
||||
|
||||
/**
|
||||
* AI 마케팅 팁 생성
|
||||
* 마케팅 팁 제공
|
||||
* 1시간 이내 팁이 있으면 기존 것 사용, 없으면 새로 생성
|
||||
*/
|
||||
MarketingTipResponse generateMarketingTips(MarketingTipRequest request);
|
||||
|
||||
/**
|
||||
* 마케팅 팁 이력 조회
|
||||
*/
|
||||
Page<MarketingTipResponse> getMarketingTipHistory(Long storeId, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 마케팅 팁 상세 조회
|
||||
*/
|
||||
MarketingTipResponse getMarketingTip(Long tipId);
|
||||
}
|
||||
MarketingTipResponse provideMarketingTip();
|
||||
}
|
||||
@ -18,8 +18,8 @@ public class WebClientConfig {
|
||||
@Bean
|
||||
public WebClient webClient() {
|
||||
HttpClient httpClient = HttpClient.create()
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
|
||||
.responseTimeout(Duration.ofMillis(5000));
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
|
||||
.responseTimeout(Duration.ofMillis(30000));
|
||||
|
||||
return WebClient.builder()
|
||||
.clientConnector(new ReactorClientHttpConnector(httpClient))
|
||||
|
||||
@ -4,6 +4,7 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.cglib.core.Local;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@ -15,19 +16,21 @@ import java.time.LocalDateTime;
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MarketingTip {
|
||||
|
||||
|
||||
private TipId id;
|
||||
private Long storeId;
|
||||
private String tipSummary;
|
||||
private String tipContent;
|
||||
private StoreData storeData;
|
||||
private StoreWithMenuData storeWithMenuData;
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public static MarketingTip create(Long storeId, String tipContent, StoreData storeData) {
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
public static MarketingTip create(Long storeId, String tipContent, StoreWithMenuData storeWithMenuData) {
|
||||
return MarketingTip.builder()
|
||||
.storeId(storeId)
|
||||
.tipContent(tipContent)
|
||||
.storeData(storeData)
|
||||
.storeWithMenuData(storeWithMenuData)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package com.won.smarketing.recommend.domain.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 메뉴 데이터 값 객체
|
||||
*/
|
||||
@Getter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MenuData {
|
||||
private Long menuId;
|
||||
private String menuName;
|
||||
private String category;
|
||||
private Integer price;
|
||||
private String description;
|
||||
}
|
||||
@ -13,7 +13,10 @@ import lombok.NoArgsConstructor;
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class StoreData {
|
||||
private Long storeId;
|
||||
private String storeName;
|
||||
private String businessType;
|
||||
private String location;
|
||||
private String description;
|
||||
private Integer seatCount;
|
||||
}
|
||||
|
||||
@ -0,0 +1,13 @@
|
||||
package com.won.smarketing.recommend.domain.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class StoreWithMenuData {
|
||||
private StoreData storeData;
|
||||
private List<MenuData> menuDataList;
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package com.won.smarketing.recommend.domain.service;
|
||||
|
||||
import com.won.smarketing.recommend.domain.model.StoreData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreWithMenuData;
|
||||
|
||||
/**
|
||||
* AI 팁 생성 도메인 서비스 인터페이스 (단순화)
|
||||
@ -10,9 +11,8 @@ public interface AiTipGenerator {
|
||||
/**
|
||||
* Python AI 서비스를 통한 마케팅 팁 생성
|
||||
*
|
||||
* @param storeData 매장 정보
|
||||
* @param additionalRequirement 추가 요청사항
|
||||
* @param storeWithMenuData 매장 및 메뉴 정보
|
||||
* @return AI가 생성한 마케팅 팁
|
||||
*/
|
||||
String generateTip(StoreData storeData, String additionalRequirement);
|
||||
String generateTip(StoreWithMenuData storeWithMenuData);
|
||||
}
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
package com.won.smarketing.recommend.domain.service;
|
||||
|
||||
import com.won.smarketing.recommend.domain.model.StoreData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreWithMenuData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 매장 데이터 제공 도메인 서비스 인터페이스
|
||||
*/
|
||||
public interface StoreDataProvider {
|
||||
|
||||
StoreData getStoreData(Long storeId);
|
||||
|
||||
StoreWithMenuData getStoreWithMenuData(String userId);
|
||||
}
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
package com.won.smarketing.recommend.infrastructure.external;
|
||||
|
||||
import com.won.smarketing.recommend.domain.model.MenuData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreWithMenuData;
|
||||
import com.won.smarketing.recommend.domain.service.AiTipGenerator;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@ -9,7 +12,11 @@ import org.springframework.stereotype.Service; // 이 어노테이션이 누락
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Python AI 팁 생성 구현체 (날씨 정보 제거)
|
||||
@ -31,37 +38,44 @@ public class PythonAiTipGenerator implements AiTipGenerator {
|
||||
private int timeout;
|
||||
|
||||
@Override
|
||||
public String generateTip(StoreData storeData, String additionalRequirement) {
|
||||
public String generateTip(StoreWithMenuData storeWithMenuData) {
|
||||
try {
|
||||
log.debug("Python AI 서비스 호출: store={}", storeData.getStoreName());
|
||||
|
||||
// Python AI 서비스 사용 가능 여부 확인
|
||||
if (isPythonServiceAvailable()) {
|
||||
return callPythonAiService(storeData, additionalRequirement);
|
||||
} else {
|
||||
log.warn("Python AI 서비스 사용 불가, Fallback 처리");
|
||||
return createFallbackTip(storeData, additionalRequirement);
|
||||
}
|
||||
log.debug("Python AI 서비스 직접 호출: store={}", storeWithMenuData.getStoreData().getStoreName());
|
||||
return callPythonAiService(storeWithMenuData);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Python AI 서비스 호출 실패, Fallback 처리: {}", e.getMessage());
|
||||
return createFallbackTip(storeData, additionalRequirement);
|
||||
return createFallbackTip(storeWithMenuData);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPythonServiceAvailable() {
|
||||
return !pythonAiServiceApiKey.equals("dummy-key");
|
||||
}
|
||||
private String callPythonAiService(StoreWithMenuData storeWithMenuData) {
|
||||
|
||||
private String callPythonAiService(StoreData storeData, String additionalRequirement) {
|
||||
try {
|
||||
// Python AI 서비스로 전송할 데이터 (날씨 정보 제거, 매장 정보만 전달)
|
||||
Map<String, Object> requestData = Map.of(
|
||||
"store_name", storeData.getStoreName(),
|
||||
"business_type", storeData.getBusinessType(),
|
||||
"location", storeData.getLocation(),
|
||||
"additional_requirement", additionalRequirement != null ? additionalRequirement : ""
|
||||
);
|
||||
|
||||
StoreData storeData = storeWithMenuData.getStoreData();
|
||||
List<MenuData> menuDataList = storeWithMenuData.getMenuDataList();
|
||||
|
||||
// 메뉴 데이터를 Map 형태로 변환
|
||||
List<Map<String, Object>> menuList = menuDataList.stream()
|
||||
.map(menu -> {
|
||||
Map<String, Object> menuMap = new HashMap<>();
|
||||
menuMap.put("menu_id", menu.getMenuId());
|
||||
menuMap.put("menu_name", menu.getMenuName());
|
||||
menuMap.put("category", menu.getCategory());
|
||||
menuMap.put("price", menu.getPrice());
|
||||
menuMap.put("description", menu.getDescription());
|
||||
return menuMap;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Python AI 서비스로 전송할 데이터 (매장 정보 + 메뉴 정보)
|
||||
Map<String, Object> requestData = new HashMap<>();
|
||||
requestData.put("store_name", storeData.getStoreName());
|
||||
requestData.put("business_type", storeData.getBusinessType());
|
||||
requestData.put("location", storeData.getLocation());
|
||||
requestData.put("seat_count", storeData.getSeatCount());
|
||||
requestData.put("menu_list", menuList);
|
||||
|
||||
log.debug("Python AI 서비스 요청 데이터: {}", requestData);
|
||||
|
||||
@ -84,22 +98,16 @@ public class PythonAiTipGenerator implements AiTipGenerator {
|
||||
log.error("Python AI 서비스 실제 호출 실패: {}", e.getMessage());
|
||||
}
|
||||
|
||||
return createFallbackTip(storeData, additionalRequirement);
|
||||
return createFallbackTip(storeWithMenuData);
|
||||
}
|
||||
|
||||
/**
|
||||
* 규칙 기반 Fallback 팁 생성 (날씨 정보 없이 매장 정보만 활용)
|
||||
*/
|
||||
private String createFallbackTip(StoreData storeData, String additionalRequirement) {
|
||||
String businessType = storeData.getBusinessType();
|
||||
String storeName = storeData.getStoreName();
|
||||
String location = storeData.getLocation();
|
||||
|
||||
// 추가 요청사항이 있는 경우 우선 반영
|
||||
if (additionalRequirement != null && !additionalRequirement.trim().isEmpty()) {
|
||||
return String.format("%s에서 %s를 중심으로 한 특별한 서비스로 고객들을 맞이해보세요!",
|
||||
storeName, additionalRequirement);
|
||||
}
|
||||
private String createFallbackTip(StoreWithMenuData storeWithMenuData) {
|
||||
String businessType = storeWithMenuData.getStoreData().getBusinessType();
|
||||
String storeName = storeWithMenuData.getStoreData().getStoreName();
|
||||
String location = storeWithMenuData.getStoreData().getLocation();
|
||||
|
||||
// 업종별 기본 팁 생성
|
||||
if (businessType.contains("카페")) {
|
||||
@ -123,16 +131,13 @@ public class PythonAiTipGenerator implements AiTipGenerator {
|
||||
return String.format("%s만의 특별함을 살린 고객 맞춤 서비스로 단골 고객을 늘려보세요!", storeName);
|
||||
}
|
||||
|
||||
@Getter
|
||||
private static class PythonAiResponse {
|
||||
private String tip;
|
||||
private String status;
|
||||
private String message;
|
||||
|
||||
public String getTip() { return tip; }
|
||||
public void setTip(String tip) { this.tip = tip; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
private LocalDateTime generatedTip;
|
||||
private String businessType;
|
||||
private String aiModel;
|
||||
}
|
||||
}
|
||||
@ -2,17 +2,29 @@ package com.won.smarketing.recommend.infrastructure.external;
|
||||
|
||||
import com.won.smarketing.common.exception.BusinessException;
|
||||
import com.won.smarketing.common.exception.ErrorCode;
|
||||
import com.won.smarketing.recommend.domain.model.MenuData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreData;
|
||||
import com.won.smarketing.recommend.domain.model.StoreWithMenuData;
|
||||
import com.won.smarketing.recommend.domain.service.StoreDataProvider;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service; // 이 어노테이션이 누락되어 있었음
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import org.springframework.web.reactive.function.client.WebClientException;
|
||||
import org.springframework.web.reactive.function.client.WebClientResponseException;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 매장 API 데이터 제공자 구현체
|
||||
@ -30,46 +42,85 @@ public class StoreApiDataProvider implements StoreDataProvider {
|
||||
@Value("${external.store-service.timeout}")
|
||||
private int timeout;
|
||||
|
||||
@Override
|
||||
@Cacheable(value = "storeData", key = "#storeId")
|
||||
public StoreData getStoreData(Long storeId) {
|
||||
try {
|
||||
log.debug("매장 정보 조회 시도: storeId={}", storeId);
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
|
||||
// 외부 서비스 연결 시도, 실패 시 Mock 데이터 반환
|
||||
if (isStoreServiceAvailable()) {
|
||||
return callStoreService(storeId);
|
||||
} else {
|
||||
log.warn("매장 서비스 연결 불가, Mock 데이터 반환: storeId={}", storeId);
|
||||
return createMockStoreData(storeId);
|
||||
}
|
||||
public StoreWithMenuData getStoreWithMenuData(String userId) {
|
||||
log.info("매장 정보와 메뉴 정보 통합 조회 시작: userId={}", userId);
|
||||
|
||||
try {
|
||||
// 매장 정보와 메뉴 정보를 병렬로 조회
|
||||
StoreData storeData = getStoreDataByUserId(userId);
|
||||
List<MenuData> menuDataList = getMenusByStoreId(storeData.getStoreId());
|
||||
|
||||
StoreWithMenuData result = StoreWithMenuData.builder()
|
||||
.storeData(storeData)
|
||||
.menuDataList(menuDataList)
|
||||
.build();
|
||||
|
||||
log.info("매장 정보와 메뉴 정보 통합 조회 완료: storeId={}, storeName={}, menuCount={}",
|
||||
storeData.getStoreId(), storeData.getStoreName(), menuDataList.size());
|
||||
|
||||
return result;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("매장 정보 조회 실패, Mock 데이터 반환: storeId={}", storeId, e);
|
||||
return createMockStoreData(storeId);
|
||||
log.error("매장 정보와 메뉴 정보 통합 조회 실패, Mock 데이터 반환: storeId={}", userId, e);
|
||||
|
||||
// 실패 시 Mock 데이터 반환
|
||||
return StoreWithMenuData.builder()
|
||||
.storeData(createMockStoreData(userId))
|
||||
.menuDataList(createMockMenuData(6L))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isStoreServiceAvailable() {
|
||||
return !storeServiceBaseUrl.equals("http://localhost:8082");
|
||||
public StoreData getStoreDataByUserId(String userId) {
|
||||
try {
|
||||
log.debug("매장 정보 실시간 조회: userId={}", userId);
|
||||
return callStoreServiceByUserId(userId);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("매장 정보 조회 실패, Mock 데이터 반환: userId={}, error={}", userId, e.getMessage());
|
||||
return createMockStoreData(userId);
|
||||
}
|
||||
}
|
||||
|
||||
private StoreData callStoreService(Long storeId) {
|
||||
|
||||
public List<MenuData> getMenusByStoreId(Long storeId) {
|
||||
log.info("매장 메뉴 조회 시작: storeId={}", storeId);
|
||||
|
||||
try {
|
||||
return callMenuService(storeId);
|
||||
} catch (Exception e) {
|
||||
log.error("메뉴 조회 실패, Mock 데이터 반환: storeId={}", storeId, e);
|
||||
return createMockMenuData(storeId);
|
||||
}
|
||||
}
|
||||
|
||||
private StoreData callStoreServiceByUserId(String userId) {
|
||||
|
||||
try {
|
||||
StoreApiResponse response = webClient
|
||||
.get()
|
||||
.uri(storeServiceBaseUrl + "/api/store/" + storeId)
|
||||
.uri(storeServiceBaseUrl + "/api/store")
|
||||
.header("Authorization", "Bearer " + getCurrentJwtToken()) // JWT 토큰 추가
|
||||
.retrieve()
|
||||
.bodyToMono(StoreApiResponse.class)
|
||||
.timeout(Duration.ofMillis(timeout))
|
||||
.block();
|
||||
|
||||
log.info("response : {}", response.getData().getStoreName());
|
||||
log.info("response : {}", response.getData().getStoreId());
|
||||
|
||||
if (response != null && response.getData() != null) {
|
||||
StoreApiResponse.StoreInfo storeInfo = response.getData();
|
||||
return StoreData.builder()
|
||||
.storeId(storeInfo.getStoreId())
|
||||
.storeName(storeInfo.getStoreName())
|
||||
.businessType(storeInfo.getBusinessType())
|
||||
.location(storeInfo.getAddress())
|
||||
.description(storeInfo.getDescription())
|
||||
.seatCount(storeInfo.getSeatCount())
|
||||
.build();
|
||||
}
|
||||
} catch (WebClientResponseException e) {
|
||||
@ -79,17 +130,118 @@ public class StoreApiDataProvider implements StoreDataProvider {
|
||||
log.error("매장 서비스 호출 실패: {}", e.getMessage());
|
||||
}
|
||||
|
||||
return createMockStoreData(storeId);
|
||||
return createMockStoreData(userId);
|
||||
}
|
||||
|
||||
private StoreData createMockStoreData(Long storeId) {
|
||||
private String getCurrentJwtToken() {
|
||||
try {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
|
||||
if (attributes == null) {
|
||||
log.warn("RequestAttributes를 찾을 수 없음 - HTTP 요청 컨텍스트 없음");
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
|
||||
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) {
|
||||
String token = bearerToken.substring(BEARER_PREFIX.length());
|
||||
log.debug("JWT 토큰 추출 성공: {}...", token.substring(0, Math.min(10, token.length())));
|
||||
return token;
|
||||
} else {
|
||||
log.warn("Authorization 헤더에서 Bearer 토큰을 찾을 수 없음: {}", bearerToken);
|
||||
return null;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("JWT 토큰 추출 중 오류 발생: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private List<MenuData> callMenuService(Long storeId) {
|
||||
try {
|
||||
MenuApiResponse response = webClient
|
||||
.get()
|
||||
.uri(storeServiceBaseUrl + "/api/menu/store/" + storeId)
|
||||
.retrieve()
|
||||
.bodyToMono(MenuApiResponse.class)
|
||||
.timeout(Duration.ofMillis(timeout))
|
||||
.block();
|
||||
|
||||
if (response != null && response.getData() != null && !response.getData().isEmpty()) {
|
||||
List<MenuData> menuDataList = response.getData().stream()
|
||||
.map(this::toMenuData)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
log.info("매장 메뉴 조회 성공: storeId={}, menuCount={}", storeId, menuDataList.size());
|
||||
return menuDataList;
|
||||
}
|
||||
} catch (WebClientResponseException e) {
|
||||
if (e.getStatusCode().value() == 404) {
|
||||
log.warn("매장의 메뉴 정보가 없습니다: storeId={}", storeId);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
log.error("메뉴 서비스 호출 실패: storeId={}, error={}", storeId, e.getMessage());
|
||||
} catch (WebClientException e) {
|
||||
log.error("메뉴 서비스 연결 실패: storeId={}, error={}", storeId, e.getMessage());
|
||||
}
|
||||
|
||||
return createMockMenuData(storeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* MenuResponse를 MenuData로 변환
|
||||
*/
|
||||
private MenuData toMenuData(MenuApiResponse.MenuInfo menuInfo) {
|
||||
return MenuData.builder()
|
||||
.menuId(menuInfo.getMenuId())
|
||||
.menuName(menuInfo.getMenuName())
|
||||
.category(menuInfo.getCategory())
|
||||
.price(menuInfo.getPrice())
|
||||
.description(menuInfo.getDescription())
|
||||
.build();
|
||||
}
|
||||
|
||||
private StoreData createMockStoreData(String userId) {
|
||||
return StoreData.builder()
|
||||
.storeName("테스트 카페 " + storeId)
|
||||
.storeName("테스트 카페 " + userId)
|
||||
.businessType("카페")
|
||||
.location("서울시 강남구")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<MenuData> createMockMenuData(Long storeId) {
|
||||
log.info("Mock 메뉴 데이터 생성: storeId={}", storeId);
|
||||
|
||||
return List.of(
|
||||
MenuData.builder()
|
||||
.menuId(1L)
|
||||
.menuName("아메리카노")
|
||||
.category("음료")
|
||||
.price(4000)
|
||||
.description("깊고 진한 맛의 아메리카노")
|
||||
.build(),
|
||||
MenuData.builder()
|
||||
.menuId(2L)
|
||||
.menuName("카페라떼")
|
||||
.category("음료")
|
||||
.price(4500)
|
||||
.description("부드러운 우유 거품이 올라간 카페라떼")
|
||||
.build(),
|
||||
MenuData.builder()
|
||||
.menuId(3L)
|
||||
.menuName("치즈케이크")
|
||||
.category("디저트")
|
||||
.price(6000)
|
||||
.description("진한 치즈 맛의 수제 케이크")
|
||||
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
@Getter
|
||||
private static class StoreApiResponse {
|
||||
private int status;
|
||||
private String message;
|
||||
@ -102,23 +254,58 @@ public class StoreApiDataProvider implements StoreDataProvider {
|
||||
public StoreInfo getData() { return data; }
|
||||
public void setData(StoreInfo data) { this.data = data; }
|
||||
|
||||
@Getter
|
||||
static class StoreInfo {
|
||||
private Long storeId;
|
||||
private String storeName;
|
||||
private String businessType;
|
||||
private String address;
|
||||
private String phoneNumber;
|
||||
private String description;
|
||||
private Integer seatCount;
|
||||
}
|
||||
}
|
||||
|
||||
public Long getStoreId() { return storeId; }
|
||||
public void setStoreId(Long storeId) { this.storeId = storeId; }
|
||||
public String getStoreName() { return storeName; }
|
||||
public void setStoreName(String storeName) { this.storeName = storeName; }
|
||||
public String getBusinessType() { return businessType; }
|
||||
public void setBusinessType(String businessType) { this.businessType = businessType; }
|
||||
public String getAddress() { return address; }
|
||||
public void setAddress(String address) { this.address = address; }
|
||||
public String getPhoneNumber() { return phoneNumber; }
|
||||
public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }
|
||||
/**
|
||||
* Menu API 응답 DTO (새로 추가)
|
||||
*/
|
||||
private static class MenuApiResponse {
|
||||
private List<MenuInfo> data;
|
||||
private String message;
|
||||
private boolean success;
|
||||
|
||||
public List<MenuInfo> getData() { return data; }
|
||||
public void setData(List<MenuInfo> data) { this.data = data; }
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
public boolean isSuccess() { return success; }
|
||||
public void setSuccess(boolean success) { this.success = success; }
|
||||
|
||||
public static class MenuInfo {
|
||||
private Long menuId;
|
||||
private String menuName;
|
||||
private String category;
|
||||
private Integer price;
|
||||
private String description;
|
||||
private String image;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
public Long getMenuId() { return menuId; }
|
||||
public void setMenuId(Long menuId) { this.menuId = menuId; }
|
||||
public String getMenuName() { return menuName; }
|
||||
public void setMenuName(String menuName) { this.menuName = menuName; }
|
||||
public String getCategory() { return category; }
|
||||
public void setCategory(String category) { this.category = category; }
|
||||
public Integer getPrice() { return price; }
|
||||
public void setPrice(Integer price) { this.price = price; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
public String getImage() { return image; }
|
||||
public void setImage(String image) { this.image = image; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -8,13 +8,14 @@ import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 마케팅 팁 JPA 엔티티 (날씨 정보 제거)
|
||||
* 마케팅 팁 JPA 엔티티
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "marketing_tips")
|
||||
@ -27,53 +28,54 @@ public class MarketingTipEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "tip_id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false, length = 50)
|
||||
private String userId;
|
||||
|
||||
@Column(name = "store_id", nullable = false)
|
||||
private Long storeId;
|
||||
|
||||
@Column(name = "tip_content", nullable = false, length = 2000)
|
||||
@Column(name = "tip_summary")
|
||||
private String tipSummary;
|
||||
|
||||
@Lob
|
||||
@Column(name = "tip_content", nullable = false, columnDefinition = "TEXT")
|
||||
private String tipContent;
|
||||
|
||||
// 매장 정보만 저장
|
||||
@Column(name = "store_name", length = 200)
|
||||
private String storeName;
|
||||
|
||||
@Column(name = "business_type", length = 100)
|
||||
private String businessType;
|
||||
|
||||
@Column(name = "store_location", length = 500)
|
||||
private String storeLocation;
|
||||
@Column(name = "ai_model")
|
||||
private String aiModel;
|
||||
|
||||
@CreatedDate
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public static MarketingTipEntity fromDomain(MarketingTip marketingTip) {
|
||||
@LastModifiedDate
|
||||
@Column(name = "updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
public static MarketingTipEntity fromDomain(MarketingTip marketingTip, String userId) {
|
||||
return MarketingTipEntity.builder()
|
||||
.id(marketingTip.getId() != null ? marketingTip.getId().getValue() : null)
|
||||
.userId(userId)
|
||||
.storeId(marketingTip.getStoreId())
|
||||
.tipContent(marketingTip.getTipContent())
|
||||
.storeName(marketingTip.getStoreData().getStoreName())
|
||||
.businessType(marketingTip.getStoreData().getBusinessType())
|
||||
.storeLocation(marketingTip.getStoreData().getLocation())
|
||||
.tipSummary(marketingTip.getTipSummary())
|
||||
.createdAt(marketingTip.getCreatedAt())
|
||||
.updatedAt(marketingTip.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
public MarketingTip toDomain() {
|
||||
StoreData storeData = StoreData.builder()
|
||||
.storeName(this.storeName)
|
||||
.businessType(this.businessType)
|
||||
.location(this.storeLocation)
|
||||
.build();
|
||||
|
||||
public MarketingTip toDomain(StoreData storeData) {
|
||||
return MarketingTip.builder()
|
||||
.id(this.id != null ? TipId.of(this.id) : null)
|
||||
.storeId(this.storeId)
|
||||
.tipSummary(this.tipSummary)
|
||||
.tipContent(this.tipContent)
|
||||
.storeData(storeData)
|
||||
.createdAt(this.createdAt)
|
||||
.updatedAt(this.updatedAt)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,12 +7,34 @@ import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 마케팅 팁 JPA 레포지토리
|
||||
*/
|
||||
@Repository
|
||||
public interface MarketingTipJpaRepository extends JpaRepository<MarketingTipEntity, Long> {
|
||||
|
||||
|
||||
/**
|
||||
* 매장별 마케팅 팁 조회 (기존 - storeId 기반)
|
||||
*/
|
||||
@Query("SELECT m FROM MarketingTipEntity m WHERE m.storeId = :storeId ORDER BY m.createdAt DESC")
|
||||
Page<MarketingTipEntity> findByStoreIdOrderByCreatedAtDesc(@Param("storeId") Long storeId, Pageable pageable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자별 마케팅 팁 조회 (새로 추가 - userId 기반)
|
||||
*/
|
||||
@Query("SELECT m FROM MarketingTipEntity m WHERE m.userId = :userId ORDER BY m.createdAt DESC")
|
||||
Page<MarketingTipEntity> findByUserIdOrderByCreatedAtDesc(@Param("userId") String userId, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 사용자의 가장 최근 마케팅 팁 조회
|
||||
*/
|
||||
@Query("SELECT m FROM MarketingTipEntity m WHERE m.userId = :userId ORDER BY m.createdAt DESC LIMIT 1")
|
||||
Optional<MarketingTipEntity> findTopByUserIdOrderByCreatedAtDesc(@Param("userId") String userId);
|
||||
|
||||
/**
|
||||
* 특정 팁이 해당 사용자의 것인지 확인
|
||||
*/
|
||||
boolean existsByIdAndUserId(Long id, String userId);
|
||||
}
|
||||
@ -1,39 +1,88 @@
|
||||
package com.won.smarketing.recommend.infrastructure.persistence;
|
||||
|
||||
import com.won.smarketing.recommend.domain.model.MarketingTip;
|
||||
import com.won.smarketing.recommend.domain.model.StoreWithMenuData;
|
||||
import com.won.smarketing.recommend.domain.repository.MarketingTipRepository;
|
||||
import com.won.smarketing.recommend.domain.service.StoreDataProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 마케팅 팁 레포지토리 구현체
|
||||
*/
|
||||
@Slf4j
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class MarketingTipRepositoryImpl implements MarketingTipRepository {
|
||||
|
||||
private final MarketingTipJpaRepository jpaRepository;
|
||||
private final StoreDataProvider storeDataProvider;
|
||||
|
||||
@Override
|
||||
public MarketingTip save(MarketingTip marketingTip) {
|
||||
MarketingTipEntity entity = MarketingTipEntity.fromDomain(marketingTip);
|
||||
String userId = getCurrentUserId();
|
||||
MarketingTipEntity entity = MarketingTipEntity.fromDomain(marketingTip, userId);
|
||||
MarketingTipEntity savedEntity = jpaRepository.save(entity);
|
||||
return savedEntity.toDomain();
|
||||
|
||||
// Store 정보는 다시 조회해서 Domain에 설정
|
||||
StoreWithMenuData storeWithMenuData = storeDataProvider.getStoreWithMenuData(userId);
|
||||
return savedEntity.toDomain(storeWithMenuData.getStoreData());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<MarketingTip> findById(Long tipId) {
|
||||
return jpaRepository.findById(tipId)
|
||||
.map(MarketingTipEntity::toDomain);
|
||||
.map(entity -> {
|
||||
// Store 정보를 API로 조회
|
||||
StoreWithMenuData storeWithMenuData = storeDataProvider.getStoreWithMenuData(entity.getUserId());
|
||||
return entity.toDomain(storeWithMenuData.getStoreData());
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<MarketingTip> findByStoreIdOrderByCreatedAtDesc(Long storeId, Pageable pageable) {
|
||||
return jpaRepository.findByStoreIdOrderByCreatedAtDesc(storeId, pageable)
|
||||
.map(MarketingTipEntity::toDomain);
|
||||
// 기존 메서드는 호환성을 위해 유지하지만, 내부적으로는 userId로 조회
|
||||
String userId = getCurrentUserId();
|
||||
return findByUserIdOrderByCreatedAtDesc(userId, pageable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자별 마케팅 팁 조회 (새로 추가)
|
||||
*/
|
||||
public Page<MarketingTip> findByUserIdOrderByCreatedAtDesc(String userId, Pageable pageable) {
|
||||
Page<MarketingTipEntity> entities = jpaRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable);
|
||||
|
||||
// Store 정보는 한 번만 조회 (같은 userId이므로)
|
||||
StoreWithMenuData storeWithMenuData = storeDataProvider.getStoreWithMenuData(userId);
|
||||
|
||||
return entities.map(entity -> entity.toDomain(storeWithMenuData.getStoreData()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 가장 최근 마케팅 팁 조회
|
||||
*/
|
||||
public Optional<MarketingTip> findMostRecentByUserId(String userId) {
|
||||
return jpaRepository.findTopByUserIdOrderByCreatedAtDesc(userId)
|
||||
.map(entity -> {
|
||||
StoreWithMenuData storeWithMenuData = storeDataProvider.getStoreWithMenuData(userId);
|
||||
return entity.toDomain(storeWithMenuData.getStoreData());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 팁이 해당 사용자의 것인지 확인
|
||||
*/
|
||||
public boolean isOwnedByUser(Long tipId, String userId) {
|
||||
return jpaRepository.existsByIdAndUserId(tipId, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 로그인된 사용자 ID 조회
|
||||
*/
|
||||
private String getCurrentUserId() {
|
||||
return SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
}
|
||||
}
|
||||
@ -2,22 +2,18 @@ package com.won.smarketing.recommend.presentation.controller;
|
||||
|
||||
import com.won.smarketing.common.dto.ApiResponse;
|
||||
import com.won.smarketing.recommend.application.usecase.MarketingTipUseCase;
|
||||
import com.won.smarketing.recommend.presentation.dto.MarketingTipRequest;
|
||||
import com.won.smarketing.recommend.presentation.dto.MarketingTipResponse;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
/**
|
||||
* AI 마케팅 추천 컨트롤러
|
||||
* AI 마케팅 추천 컨트롤러 (단일 API)
|
||||
*/
|
||||
@Tag(name = "AI 추천", description = "AI 기반 마케팅 팁 추천 API")
|
||||
@Slf4j
|
||||
@ -29,49 +25,17 @@ public class RecommendationController {
|
||||
private final MarketingTipUseCase marketingTipUseCase;
|
||||
|
||||
@Operation(
|
||||
summary = "AI 마케팅 팁 생성",
|
||||
description = "매장 정보를 기반으로 Python AI 서비스에서 마케팅 팁을 생성합니다."
|
||||
summary = "마케팅 팁 조회/생성",
|
||||
description = "마케팅 팁 전체 내용 조회. 1시간 이내 생성된 팁이 있으면 기존 것 사용, 없으면 새로 생성"
|
||||
)
|
||||
@PostMapping("/marketing-tips")
|
||||
public ResponseEntity<ApiResponse<MarketingTipResponse>> generateMarketingTips(
|
||||
@Parameter(description = "마케팅 팁 생성 요청") @Valid @RequestBody MarketingTipRequest request) {
|
||||
|
||||
log.info("AI 마케팅 팁 생성 요청: storeId={}", request.getStoreId());
|
||||
|
||||
MarketingTipResponse response = marketingTipUseCase.generateMarketingTips(request);
|
||||
|
||||
log.info("AI 마케팅 팁 생성 완료: tipId={}", response.getTipId());
|
||||
return ResponseEntity.ok(ApiResponse.success(response));
|
||||
}
|
||||
public ResponseEntity<ApiResponse<MarketingTipResponse>> provideMarketingTip() {
|
||||
|
||||
@Operation(
|
||||
summary = "마케팅 팁 이력 조회",
|
||||
description = "특정 매장의 마케팅 팁 생성 이력을 조회합니다."
|
||||
)
|
||||
@GetMapping("/marketing-tips")
|
||||
public ResponseEntity<ApiResponse<Page<MarketingTipResponse>>> getMarketingTipHistory(
|
||||
@Parameter(description = "매장 ID") @RequestParam Long storeId,
|
||||
Pageable pageable) {
|
||||
log.info("마케팅 팁 제공 요청");
|
||||
|
||||
log.info("마케팅 팁 이력 조회: storeId={}, page={}", storeId, pageable.getPageNumber());
|
||||
MarketingTipResponse response = marketingTipUseCase.provideMarketingTip();
|
||||
|
||||
Page<MarketingTipResponse> response = marketingTipUseCase.getMarketingTipHistory(storeId, pageable);
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.success(response));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "마케팅 팁 상세 조회",
|
||||
description = "특정 마케팅 팁의 상세 정보를 조회합니다."
|
||||
)
|
||||
@GetMapping("/marketing-tips/{tipId}")
|
||||
public ResponseEntity<ApiResponse<MarketingTipResponse>> getMarketingTip(
|
||||
@Parameter(description = "팁 ID") @PathVariable Long tipId) {
|
||||
|
||||
log.info("마케팅 팁 상세 조회: tipId={}", tipId);
|
||||
|
||||
MarketingTipResponse response = marketingTipUseCase.getMarketingTip(tipId);
|
||||
|
||||
log.info("마케팅 팁 제공 완료: tipId={}", response.getTipId());
|
||||
return ResponseEntity.ok(ApiResponse.success(response));
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,26 +0,0 @@
|
||||
package com.won.smarketing.recommend.presentation.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
|
||||
@Schema(description = "마케팅 팁 생성 요청")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MarketingTipRequest {
|
||||
|
||||
@Schema(description = "매장 ID", example = "1", required = true)
|
||||
@NotNull(message = "매장 ID는 필수입니다")
|
||||
@Positive(message = "매장 ID는 양수여야 합니다")
|
||||
private Long storeId;
|
||||
|
||||
@Schema(description = "추가 요청사항", example = "여름철 음료 프로모션에 집중해주세요")
|
||||
private String additionalRequirement;
|
||||
}
|
||||
@ -8,43 +8,50 @@ import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "마케팅 팁 응답")
|
||||
/**
|
||||
* 마케팅 팁 응답 DTO (요약 + 상세 통합)
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "마케팅 팁 응답")
|
||||
public class MarketingTipResponse {
|
||||
|
||||
@Schema(description = "팁 ID", example = "1")
|
||||
private Long tipId;
|
||||
|
||||
@Schema(description = "매장 ID", example = "1")
|
||||
private Long storeId;
|
||||
@Schema(description = "마케팅 팁 요약 (1줄)", example = "가을 시즌 특별 음료로 고객들의 관심을 끌어보세요!")
|
||||
private String tipSummary;
|
||||
|
||||
@Schema(description = "매장명", example = "카페 봄날")
|
||||
private String storeName;
|
||||
|
||||
@Schema(description = "AI 생성 마케팅 팁 내용")
|
||||
@Schema(description = "마케팅 팁 전체 내용", example = "가을이 다가오면서 고객들은 따뜻하고 계절감 있는 음료를 찾게 됩니다...")
|
||||
private String tipContent;
|
||||
|
||||
@Schema(description = "매장 정보")
|
||||
private StoreInfo storeInfo;
|
||||
|
||||
@Schema(description = "생성 일시")
|
||||
@Schema(description = "생성 시간", example = "2025-06-13T14:30:00")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Schema(description = "수정 시간", example = "2025-06-13T14:30:00")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@Schema(description = "1시간 이내 생성 여부", example = "true")
|
||||
private boolean isRecentlyCreated;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "매장 정보")
|
||||
public static class StoreInfo {
|
||||
@Schema(description = "매장명", example = "카페 봄날")
|
||||
@Schema(description = "매장명", example = "민코의 카페")
|
||||
private String storeName;
|
||||
|
||||
@Schema(description = "업종", example = "카페")
|
||||
private String businessType;
|
||||
|
||||
@Schema(description = "위치", example = "서울시 강남구")
|
||||
@Schema(description = "위치", example = "서울시 강남구 테헤란로 123")
|
||||
private String location;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -12,7 +12,7 @@ spring:
|
||||
password: ${POSTGRES_PASSWORD:postgres}
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: ${JPA_DDL_AUTO:update}
|
||||
ddl-auto: ${JPA_DDL_AUTO:create-drop}
|
||||
show-sql: ${JPA_SHOW_SQL:true}
|
||||
properties:
|
||||
hibernate:
|
||||
@ -29,7 +29,7 @@ external:
|
||||
base-url: ${STORE_SERVICE_URL:http://localhost:8082}
|
||||
timeout: ${STORE_SERVICE_TIMEOUT:5000}
|
||||
python-ai-service:
|
||||
base-url: ${PYTHON_AI_SERVICE_URL:http://localhost:8090}
|
||||
base-url: ${PYTHON_AI_SERVICE_URL:http://localhost:5001}
|
||||
api-key: ${PYTHON_AI_API_KEY:dummy-key}
|
||||
timeout: ${PYTHON_AI_TIMEOUT:30000}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user