feat: 제품 검색 페이지 및 QR 라벨 인쇄 기능

- /admin/products: 전체 제품 검색 페이지 (OTC)
- /api/products: 제품 검색 API (세트상품 바코드 포함)
- qr_printer.py: Brother QL-710W 프린터 연동
- /api/qr-print, /api/qr-preview: QR 라벨 인쇄/미리보기 API
- 판매상세 페이지에 QR 인쇄 버튼 추가
- 수량 선택 UI (+/- 버튼, 최대 10장)
- 세트상품 제조사 표시 개선
- 대시보드 헤더에 제품검색/판매조회 탭 추가
This commit is contained in:
thug0bin 2026-02-27 13:56:26 +09:00
parent f3fa4707ac
commit 9bd2174501
11 changed files with 1950 additions and 8 deletions

View File

@ -2461,6 +2461,93 @@ def admin_sales_detail():
return render_template('admin_sales_detail.html')
# ===== 제품 검색 페이지 =====
@app.route('/admin/products')
def admin_products():
"""제품 검색 페이지 (전체 재고에서 검색, QR 인쇄)"""
return render_template('admin_products.html')
@app.route('/api/products')
def api_products():
"""
제품 검색 API
- 상품명, 상품코드, 바코드로 검색
- 세트상품 바코드도 CD_ITEM_UNIT_MEMBER에서 조회
"""
search = request.args.get('search', '').strip()
limit = int(request.args.get('limit', 100))
if not search or len(search) < 2:
return jsonify({'success': False, 'error': '검색어는 2글자 이상 입력하세요'})
try:
drug_session = db_manager.get_session('PM_DRUG')
# 제품 검색 쿼리
# CD_GOODS.BARCODE가 없으면 CD_ITEM_UNIT_MEMBER.CD_CD_BARCODE 사용 (세트상품)
# 세트상품 여부 확인: CD_item_set에 SetCode로 존재하면 세트상품
products_query = text(f"""
SELECT TOP {limit}
G.DrugCode as drug_code,
G.GoodsName as product_name,
COALESCE(NULLIF(G.BARCODE, ''), U.CD_CD_BARCODE, '') as barcode,
G.Saleprice as sale_price,
G.Price as cost_price,
CASE
WHEN G.SplName IS NOT NULL AND G.SplName != '' THEN G.SplName
WHEN SET_CHK.is_set = 1 THEN N'세트상품'
ELSE ''
END as supplier,
CASE WHEN SET_CHK.is_set = 1 THEN 1 ELSE 0 END as is_set
FROM CD_GOODS G
OUTER APPLY (
SELECT TOP 1 CD_CD_BARCODE
FROM CD_ITEM_UNIT_MEMBER
WHERE DRUGCODE = G.DrugCode AND CD_CD_BARCODE IS NOT NULL AND CD_CD_BARCODE != ''
) U
OUTER APPLY (
SELECT TOP 1 1 as is_set
FROM CD_item_set
WHERE SetCode = G.DrugCode AND DrugCode = 'SET0000'
) SET_CHK
WHERE
G.GoodsName LIKE :search_like
OR G.DrugCode LIKE :search_like
OR G.BARCODE LIKE :search_like
OR U.CD_CD_BARCODE LIKE :search_like
ORDER BY G.GoodsName
""")
search_like = f'%{search}%'
rows = drug_session.execute(products_query, {
'search_like': search_like
}).fetchall()
items = []
for row in rows:
items.append({
'drug_code': row.drug_code or '',
'product_name': row.product_name or '',
'barcode': row.barcode or '',
'sale_price': float(row.sale_price) if row.sale_price else 0,
'cost_price': float(row.cost_price) if row.cost_price else 0,
'supplier': row.supplier or '',
'is_set': bool(row.is_set)
})
return jsonify({
'success': True,
'items': items,
'count': len(items)
})
except Exception as e:
logging.error(f"제품 검색 오류: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/admin/sales')
def admin_sales_pos():
"""판매 내역 페이지 (POS 스타일, 거래별 그룹핑)"""
@ -2483,6 +2570,7 @@ def api_sales_detail():
# 판매 내역 조회 (최근 N일)
# CD_GOODS.BARCODE가 없으면 CD_ITEM_UNIT_MEMBER.CD_CD_BARCODE 사용 (세트상품/자체등록 바코드)
# 세트상품 여부 확인: CD_item_set에 SetCode로 존재하면 세트상품
sales_query = text("""
SELECT
S.SL_DT_appl as sale_date,
@ -2490,7 +2578,11 @@ def api_sales_detail():
S.DrugCode as drug_code,
ISNULL(G.GoodsName, '알 수 없음') as product_name,
COALESCE(NULLIF(G.BARCODE, ''), U.CD_CD_BARCODE, '') as barcode,
ISNULL(G.SplName, '') as supplier,
CASE
WHEN G.SplName IS NOT NULL AND G.SplName != '' THEN G.SplName
WHEN SET_CHK.is_set = 1 THEN '세트상품'
ELSE ''
END as supplier,
ISNULL(S.QUAN, 1) as quantity,
ISNULL(S.SL_TOTAL_PRICE, 0) as total_price_db,
ISNULL(G.Saleprice, 0) as unit_price
@ -2501,6 +2593,11 @@ def api_sales_detail():
FROM PM_DRUG.dbo.CD_ITEM_UNIT_MEMBER
WHERE DRUGCODE = S.DrugCode AND CD_CD_BARCODE IS NOT NULL AND CD_CD_BARCODE != ''
) U
OUTER APPLY (
SELECT TOP 1 1 as is_set
FROM PM_DRUG.dbo.CD_item_set
WHERE SetCode = S.DrugCode AND DrugCode = 'SET0000'
) SET_CHK
WHERE S.SL_DT_appl >= CONVERT(VARCHAR(8), DATEADD(DAY, -:days, GETDATE()), 112)
ORDER BY S.SL_DT_appl DESC, S.SL_NO_order DESC
""")
@ -2745,6 +2842,84 @@ def api_claude_status():
}), 500
# =============================================================================
# QR 라벨 인쇄 API
# =============================================================================
@app.route('/api/qr-print', methods=['POST'])
def api_qr_print():
"""QR 라벨 인쇄 API"""
try:
from qr_printer import print_drug_qr_label
data = request.get_json()
if not data:
return jsonify({'success': False, 'error': '데이터가 없습니다'}), 400
drug_name = data.get('drug_name', '')
barcode = data.get('barcode', '')
drug_code = data.get('drug_code', '')
sale_price = data.get('sale_price', 0)
if not drug_name:
return jsonify({'success': False, 'error': '상품명이 필요합니다'}), 400
# 바코드가 없으면 drug_code 사용
qr_data = barcode if barcode else drug_code
result = print_drug_qr_label(
drug_name=drug_name,
barcode=qr_data,
sale_price=sale_price,
drug_code=drug_code,
pharmacy_name='청춘약국'
)
return jsonify(result)
except ImportError as e:
logging.error(f"QR 프린터 모듈 로드 실패: {e}")
return jsonify({'success': False, 'error': 'QR 프린터 모듈이 없습니다'}), 500
except Exception as e:
logging.error(f"QR 인쇄 오류: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/qr-preview', methods=['POST'])
def api_qr_preview():
"""QR 라벨 미리보기 API (base64 이미지 반환)"""
try:
from qr_printer import preview_qr_label
data = request.get_json()
if not data:
return jsonify({'success': False, 'error': '데이터가 없습니다'}), 400
drug_name = data.get('drug_name', '')
barcode = data.get('barcode', '')
drug_code = data.get('drug_code', '')
sale_price = data.get('sale_price', 0)
if not drug_name:
return jsonify({'success': False, 'error': '상품명이 필요합니다'}), 400
qr_data = barcode if barcode else drug_code
image_data = preview_qr_label(
drug_name=drug_name,
barcode=qr_data,
sale_price=sale_price,
drug_code=drug_code,
pharmacy_name='청춘약국'
)
return jsonify({'success': True, 'image': image_data})
except Exception as e:
logging.error(f"QR 미리보기 오류: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
if __name__ == '__main__':
# 개발 모드로 실행
app.run(host='0.0.0.0', port=7001, debug=True)

121
backend/gui/check_cash.py Normal file
View File

@ -0,0 +1,121 @@
import pyodbc, sys
sys.stdout.reconfigure(encoding='utf-8')
conn = pyodbc.connect(
r'DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.0.4\PM2014;DATABASE=PM_PRES;UID=sa;PWD=tmddls214!%(;Encrypt=no;TrustServerCertificate=yes;'
)
cur = conn.cursor()
# 조제 주문(180)이 SALE_MAIN에 있는지 확인
cur.execute("""
SELECT SL_NO_order, SL_DT_appl, SL_NM_custom, SL_MY_sale, InsertTime, PRESERIAL
FROM SALE_MAIN
WHERE SL_NO_order = '20260225000180'
""")
r = cur.fetchone()
print(f'=== 조제 주문 180 in SALE_MAIN: {"있음" if r else "없음"} ===')
if r:
print(f' 주문={r[0]} 날짜={r[1]} 고객={r[2]} 금액={r[3]} 시간={r[4]} PRESERIAL={r[5]}')
# SALE_MAIN 총 건수 vs CD_SUNAB 총 건수
cur.execute("SELECT COUNT(*) FROM SALE_MAIN WHERE SL_DT_appl = '20260225'")
sale_cnt = cur.fetchone()[0]
cur.execute("SELECT COUNT(*) FROM CD_SUNAB WHERE INDATE = '20260225'")
sunab_cnt = cur.fetchone()[0]
print(f'\n=== 오늘 건수 비교 ===')
print(f' SALE_MAIN: {sale_cnt}')
print(f' CD_SUNAB: {sunab_cnt}')
# CD_SUNAB 컬럼 구조 확인
cur.execute("SELECT TOP 1 * FROM CD_SUNAB WHERE INDATE = '20260225'")
cols = [d[0] for d in cur.description]
print(f'\n=== CD_SUNAB 컬럼 ({len(cols)}개) ===')
for i, c in enumerate(cols):
print(f' {i}: {c}')
# CD_SUNAB 조제건(SALE_MAIN 없는 91건)의 PRESERIAL vs PS_main.PreSerial 매칭
cur.execute("""
SELECT S.PRESERIAL
FROM CD_SUNAB S
WHERE S.INDATE = '20260225'
AND NOT EXISTS (SELECT 1 FROM SALE_MAIN M WHERE M.SL_NO_order = S.PRESERIAL)
""")
sunab_only = [r[0] for r in cur.fetchall()]
print(f'\n=== CD_SUNAB만 있는 91건 vs PS_main 매칭 ===')
# PS_main의 PreSerial 패턴 확인
cur.execute("SELECT TOP 5 PreSerial, Day_Serial, Indate, Paname FROM PS_main WHERE Indate = '20260225' ORDER BY PreSerial DESC")
print('PS_main 샘플:')
for r in cur.fetchall():
print(f' PreSerial={r[0]} | Day_Serial={r[1]} | Indate={r[2]} | 환자={r[3]}')
# CD_SUNAB PRESERIAL vs PS_main PreSerial 직접 비교
# CD_SUNAB.PRESERIAL = '20260225000180' 형태
# PS_main.PreSerial = ? 형태 확인
cur.execute("""
SELECT COUNT(*)
FROM CD_SUNAB S
WHERE S.INDATE = '20260225'
AND NOT EXISTS (SELECT 1 FROM SALE_MAIN M WHERE M.SL_NO_order = S.PRESERIAL)
AND EXISTS (SELECT 1 FROM PS_main P WHERE P.PreSerial = S.PRESERIAL AND P.Indate = '20260225')
""")
matched = cur.fetchone()[0]
cur.execute("""
SELECT S.PRESERIAL
FROM CD_SUNAB S
WHERE S.INDATE = '20260225'
AND NOT EXISTS (SELECT 1 FROM SALE_MAIN M WHERE M.SL_NO_order = S.PRESERIAL)
AND NOT EXISTS (SELECT 1 FROM PS_main P WHERE P.PreSerial = S.PRESERIAL AND P.Indate = '20260225')
""")
unmatched = cur.fetchall()
print(f'\nCD_SUNAB 91건 중 PS_main 매칭: {matched}')
print(f'CD_SUNAB 91건 중 PS_main 미매칭: {len(unmatched)}')
for r in unmatched:
serial = r[0]
print(f'\n=== 미매칭 {serial} ===')
# CD_SUNAB에서 금액, 승인일시
cur.execute("""
SELECT ISNULL(ETC_CARD,0)+ISNULL(ETC_CASH,0) as etc,
ISNULL(OTC_CARD,0)+ISNULL(OTC_CASH,0) as otc,
APPR_DATE, CUSCODE, DaeRiSunab, YOHUDATE
FROM CD_SUNAB WHERE PRESERIAL = ? AND INDATE = '20260225'
""", serial)
d = cur.fetchone()
print(f' ETC={d[0]:,.0f} OTC={d[1]:,.0f} | 승인일시={d[2]} | CUSCODE={d[3]} | 대리수납={d[4]} | 요후일={d[5]}')
# 다른 날짜의 PS_main에서 같은 PRESERIAL 검색 (날짜 무관)
cur.execute("SELECT PreSerial, Indate, Paname, Day_Serial FROM PS_main WHERE PreSerial = ?", serial)
ps = cur.fetchone()
if ps:
print(f' → PS_main 발견! 날짜={ps[1]} 환자={ps[2]} Day_Serial={ps[3]}')
else:
print(f' → PS_main 전체에서도 없음')
# PRESERIAL 번호 앞 8자리가 다른 날짜인 CD_SUNAB 검색
cur.execute("""
SELECT INDATE, PRESERIAL, ISNULL(ETC_CARD,0)+ISNULL(ETC_CASH,0) as etc
FROM CD_SUNAB WHERE PRESERIAL = ? AND INDATE != '20260225'
""", serial)
other = cur.fetchall()
if other:
for o in other:
print(f' → 다른 날짜 CD_SUNAB 발견! INDATE={o[0]} ETC={o[2]:,.0f}')
# CUSCODE로 PS_main 검색 (같은 환자의 이전 처방?)
if d[3] and d[3].strip():
cur.execute("""
SELECT TOP 3 PreSerial, Indate, Paname, Day_Serial
FROM PS_main WHERE CusCode = ?
ORDER BY Indate DESC, Day_Serial DESC
""", d[3].strip())
ps_list = cur.fetchall()
if ps_list:
print(f' → 같은 CUSCODE({d[3]})의 최근 PS_main:')
for p in ps_list:
print(f' PreSerial={p[0]} 날짜={p[1]} 환자={p[2]}')
conn.close()

View File

@ -0,0 +1,49 @@
import pyodbc, sys
sys.stdout.reconfigure(encoding='utf-8')
conn = pyodbc.connect(
r'DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.0.4\PM2014;DATABASE=PM_PRES;UID=sa;PWD=tmddls214!%(;Encrypt=no;TrustServerCertificate=yes;'
)
cur = conn.cursor()
# 오늘 현금영수증 발행 건 확인
cur.execute("""
SELECT
PRESERIAL,
ETC_CASH, OTC_CASH, ETC_CARD, OTC_CARD,
nCASHINMODE, nAPPROVAL_NUM, nCHK_GUBUN
FROM CD_SUNAB
WHERE INDATE = '20260225'
AND nAPPROVAL_NUM IS NOT NULL AND nAPPROVAL_NUM != ''
ORDER BY PRESERIAL DESC
""")
rows = cur.fetchall()
print(f'=== 오늘 현금영수증 발행 건: {len(rows)}건 ===')
for r in rows:
cash = (r[1] or 0) + (r[2] or 0)
card = (r[3] or 0) + (r[4] or 0)
pay = '카드' if card > 0 else '현금' if cash > 0 else '?'
print(f' 주문={r[0]} | {pay} | 현금={cash:,} 카드={card:,} | 영수증모드={r[5]} | 승인번호={r[6]} | 구분={r[7]}')
# 오늘 전체 현금 결제 건 (영수증 무관)
cur.execute("""
SELECT COUNT(*) FROM CD_SUNAB
WHERE INDATE = '20260225'
AND (ETC_CASH > 0 OR OTC_CASH > 0)
""")
r = cur.fetchone()
print(f'\n=== 오늘 현금 결제 건: {r[0]}건 ===')
# 오늘 nCASHINMODE가 있는 건 (영수증 입력 방식 있음)
cur.execute("""
SELECT nCASHINMODE, COUNT(*) as cnt
FROM CD_SUNAB
WHERE INDATE = '20260225'
AND nCASHINMODE IS NOT NULL AND nCASHINMODE != ''
GROUP BY nCASHINMODE
""")
print(f'\n=== 오늘 nCASHINMODE 분포 ===')
for r in cur.fetchall():
print(f' 모드={r[0]}{r[1]}')
conn.close()

262
backend/qr_printer.py Normal file
View File

@ -0,0 +1,262 @@
# qr_printer.py - Brother QL-710W QR 라벨 인쇄
# person-lookup-web-local/print_label.py에서 핵심 기능만 추출
from PIL import Image, ImageDraw, ImageFont
import io
import logging
import qrcode
# 프린터 설정
PRINTER_IP = "192.168.0.121"
PRINTER_MODEL = "QL-710W"
LABEL_TYPE = "29" # 29mm 연속 출력 용지
# Windows 폰트 경로
FONT_PATH = "C:/Windows/Fonts/malgunbd.ttf"
logging.basicConfig(level=logging.INFO)
def create_drug_qr_label(drug_name, barcode, sale_price, drug_code=None, pharmacy_name='청춘약국'):
"""
약품 QR 라벨 이미지 생성
Parameters:
drug_name (str): 약품명
barcode (str): 바코드 (QR 코드로 변환)
sale_price (float): 판매가격
drug_code (str, optional): 약품 코드 (바코드가 없을 대체)
pharmacy_name (str, optional): 약국 이름
Returns:
PIL.Image: 생성된 라벨 이미지
"""
label_width = 306
label_height = 380
image = Image.new("1", (label_width, label_height), "white")
draw = ImageDraw.Draw(image)
# 폰트 설정
try:
drug_name_font = ImageFont.truetype(FONT_PATH, 32)
price_font = ImageFont.truetype(FONT_PATH, 36)
label_font = ImageFont.truetype(FONT_PATH, 24)
except IOError:
drug_name_font = ImageFont.load_default()
price_font = ImageFont.load_default()
label_font = ImageFont.load_default()
logging.warning("폰트 로드 실패. 기본 폰트 사용.")
# 바코드가 없으면 약품 코드 사용
qr_data = barcode if barcode else (drug_code if drug_code else "NO_BARCODE")
# QR 코드 생성
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=4,
border=1,
)
qr.add_data(qr_data)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black", back_color="white")
# QR 코드 크기 조정 및 배치
qr_size = 130
qr_img = qr_img.resize((qr_size, qr_size), Image.LANCZOS)
qr_x = (label_width - qr_size) // 2
qr_y = 15
if qr_img.mode != '1':
qr_img = qr_img.convert('1')
image.paste(qr_img, (qr_x, qr_y))
# 약품명 (QR 코드 아래)
y_position = qr_y + qr_size + 10
def draw_wrapped_text(draw, text, y, font, max_width):
"""텍스트를 여러 줄로 표시"""
chars = list(text)
lines = []
current_line = ""
for char in chars:
test_line = current_line + char
bbox = draw.textbbox((0, 0), test_line, font=font)
w = bbox[2] - bbox[0]
if w <= max_width:
current_line = test_line
else:
if current_line:
lines.append(current_line)
current_line = char
if current_line:
lines.append(current_line)
lines = lines[:2] # 최대 2줄
for line in lines:
bbox = draw.textbbox((0, 0), line, font=font)
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
draw.text(((label_width - w) / 2, y), line, font=font, fill="black")
y += h + 5
return y
y_position = draw_wrapped_text(draw, drug_name, y_position, drug_name_font, label_width - 40)
y_position += 8
# 가격
if sale_price and sale_price > 0:
price_text = f"{int(sale_price):,}"
else:
price_text = "가격 미정"
bbox = draw.textbbox((0, 0), price_text, font=price_font)
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
draw.text(((label_width - w) / 2, y_position), price_text, font=price_font, fill="black")
y_position += h + 15
# 구분선
line_margin = 30
draw.line([(line_margin, y_position), (label_width - line_margin, y_position)], fill="black", width=2)
y_position += 20
# 약국 이름
signature_text = " ".join(pharmacy_name)
bbox = draw.textbbox((0, 0), signature_text, font=label_font)
w_sig, h_sig = bbox[2] - bbox[0], bbox[3] - bbox[1]
padding = 10
box_x = (label_width - w_sig) / 2 - padding
box_y = y_position
box_x2 = box_x + w_sig + 2 * padding
box_y2 = box_y + h_sig + 2 * padding
draw.rectangle([(box_x, box_y), (box_x2, box_y2)], outline="black", width=2)
draw.text(((label_width - w_sig) / 2, box_y + padding), signature_text, font=label_font, fill="black")
# 절취선 테두리
draw_scissor_border(draw, label_width, label_height)
return image
def draw_scissor_border(draw, width, height, edge_size=10, steps=20):
"""절취선 테두리"""
# 상단
top_points = []
step_x = width / (steps * 2)
for i in range(steps * 2 + 1):
x = i * step_x
y = 0 if i % 2 == 0 else edge_size
top_points.append((int(x), int(y)))
draw.line(top_points, fill="black", width=2)
# 하단
bottom_points = []
for i in range(steps * 2 + 1):
x = i * step_x
y = height if i % 2 == 0 else height - edge_size
bottom_points.append((int(x), int(y)))
draw.line(bottom_points, fill="black", width=2)
# 좌측
left_points = []
step_y = height / (steps * 2)
for i in range(steps * 2 + 1):
y = i * step_y
x = 0 if i % 2 == 0 else edge_size
left_points.append((int(x), int(y)))
draw.line(left_points, fill="black", width=2)
# 우측
right_points = []
for i in range(steps * 2 + 1):
y = i * step_y
x = width if i % 2 == 0 else width - edge_size
right_points.append((int(x), int(y)))
draw.line(right_points, fill="black", width=2)
def print_drug_qr_label(drug_name, barcode, sale_price, drug_code=None, pharmacy_name='청춘약국'):
"""
약품 QR 라벨 인쇄 실행
Parameters:
drug_name (str): 약품명
barcode (str): 바코드
sale_price (float): 판매가격
drug_code (str, optional): 약품 코드
pharmacy_name (str, optional): 약국 이름
Returns:
dict: 성공/실패 결과
"""
try:
from brother_ql.raster import BrotherQLRaster
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
label_image = create_drug_qr_label(drug_name, barcode, sale_price, drug_code, pharmacy_name)
# 이미지를 메모리 스트림으로 변환
image_stream = io.BytesIO()
label_image.save(image_stream, format="PNG")
image_stream.seek(0)
# Brother QL 프린터로 전송
qlr = BrotherQLRaster(PRINTER_MODEL)
instructions = convert(
qlr=qlr,
images=[Image.open(image_stream)],
label=LABEL_TYPE,
rotate="0",
threshold=70.0,
dither=False,
compress=False,
lq=True,
red=False
)
send(instructions, printer_identifier=f"tcp://{PRINTER_IP}:9100")
logging.info(f"QR 라벨 인쇄 성공: {drug_name}, 바코드={barcode}")
return {"success": True, "message": f"{drug_name} QR 라벨 인쇄 완료"}
except ImportError as e:
logging.error(f"brother_ql 라이브러리 없음: {e}")
return {"success": False, "error": "brother_ql 라이브러리가 설치되지 않았습니다"}
except Exception as e:
logging.error(f"QR 라벨 인쇄 실패: {e}")
return {"success": False, "error": str(e)}
def preview_qr_label(drug_name, barcode, sale_price, drug_code=None, pharmacy_name='청춘약국'):
"""
QR 라벨 미리보기 (base64 이미지 반환)
"""
import base64
label_image = create_drug_qr_label(drug_name, barcode, sale_price, drug_code, pharmacy_name)
# PNG로 변환
image_stream = io.BytesIO()
# 1-bit 이미지를 RGB로 변환하여 더 깔끔하게
rgb_image = label_image.convert('RGB')
rgb_image.save(image_stream, format="PNG")
image_stream.seek(0)
base64_image = base64.b64encode(image_stream.read()).decode('utf-8')
return f"data:image/png;base64,{base64_image}"
if __name__ == "__main__":
# 테스트
result = print_drug_qr_label(
drug_name="벤포파워Z",
barcode="8806418067510",
sale_price=3000,
pharmacy_name="청춘약국"
)
print(result)

View File

@ -399,6 +399,8 @@
<div class="header-subtitle">청춘약국 마일리지 관리</div>
</div>
<div style="display:flex;gap:8px;">
<a href="/admin/products" style="color:rgba(255,255,255,0.9);text-decoration:none;font-size:14px;padding:8px 16px;border-radius:8px;background:rgba(255,255,255,0.15);transition:all 0.2s;">🔍 제품검색</a>
<a href="/admin/sales-detail" style="color:rgba(255,255,255,0.9);text-decoration:none;font-size:14px;padding:8px 16px;border-radius:8px;background:rgba(255,255,255,0.15);transition:all 0.2s;">📋 판매조회</a>
<a href="/admin/sales" style="color:rgba(255,255,255,0.9);text-decoration:none;font-size:14px;padding:8px 16px;border-radius:8px;background:rgba(255,255,255,0.15);transition:all 0.2s;">🧾 판매내역</a>
<a href="/admin/ai-crm" style="color:rgba(255,255,255,0.9);text-decoration:none;font-size:14px;padding:8px 16px;border-radius:8px;background:rgba(255,255,255,0.15);transition:all 0.2s;">🤖 AI CRM</a>
<a href="/admin/alimtalk" style="color:rgba(255,255,255,0.9);text-decoration:none;font-size:14px;padding:8px 16px;border-radius:8px;background:rgba(255,255,255,0.15);transition:all 0.2s;">📨 알림톡</a>

View File

@ -258,7 +258,10 @@
<div class="header">
<div class="header-nav">
<a href="/admin">← 관리자 홈</a>
<a href="/admin/alimtalk">알림톡 로그 →</a>
<div>
<a href="/admin/ai-gw" style="margin-right: 16px;">Gateway 모니터</a>
<a href="/admin/alimtalk">알림톡 로그 →</a>
</div>
</div>
<h1>AI 업셀링 CRM</h1>
<p>구매 기반 맞춤 추천 생성 현황 · Clawdbot Gateway</p>

View File

@ -299,6 +299,8 @@
</div>
<div class="header-nav">
<a href="/admin">관리자 홈</a>
<a href="/admin/ai-crm">AI 업셀링</a>
<a href="/admin/ai-gw">Gateway 모니터</a>
</div>
</div>
</div>

View File

@ -0,0 +1,607 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>제품 검색 - 청춘약국</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
background: #f8fafc;
-webkit-font-smoothing: antialiased;
color: #1e293b;
}
/* ── 헤더 ── */
.header {
background: linear-gradient(135deg, #7c3aed 0%, #8b5cf6 50%, #a78bfa 100%);
padding: 28px 32px 24px;
color: #fff;
}
.header-nav {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.header-nav a {
color: rgba(255,255,255,0.8);
text-decoration: none;
font-size: 14px;
font-weight: 500;
}
.header-nav a:hover { color: #fff; }
.header h1 {
font-size: 24px;
font-weight: 700;
letter-spacing: -0.5px;
margin-bottom: 6px;
}
.header p {
font-size: 14px;
opacity: 0.85;
}
/* ── 컨텐츠 ── */
.content {
max-width: 1200px;
margin: 0 auto;
padding: 24px 20px 60px;
}
/* ── 검색 영역 ── */
.search-section {
background: #fff;
border-radius: 14px;
padding: 24px;
margin-bottom: 20px;
border: 1px solid #e2e8f0;
}
.search-box {
display: flex;
gap: 12px;
}
.search-input {
flex: 1;
padding: 14px 18px;
border: 2px solid #e2e8f0;
border-radius: 12px;
font-size: 16px;
font-family: inherit;
transition: all 0.2s;
}
.search-input:focus {
outline: none;
border-color: #8b5cf6;
box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1);
}
.search-input::placeholder {
color: #94a3b8;
}
.search-btn {
background: #8b5cf6;
color: #fff;
border: none;
padding: 14px 32px;
border-radius: 12px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.search-btn:hover { background: #7c3aed; }
.search-btn:active { transform: scale(0.98); }
.search-hint {
margin-top: 12px;
font-size: 13px;
color: #94a3b8;
}
.search-hint span {
background: #f1f5f9;
padding: 2px 8px;
border-radius: 4px;
margin-right: 8px;
}
/* ── 결과 카운트 ── */
.result-count {
margin-bottom: 16px;
font-size: 14px;
color: #64748b;
}
.result-count strong {
color: #8b5cf6;
font-weight: 700;
}
/* ── 테이블 ── */
.table-wrap {
background: #fff;
border-radius: 14px;
border: 1px solid #e2e8f0;
overflow: hidden;
}
table {
width: 100%;
border-collapse: collapse;
}
thead th {
background: #f8fafc;
padding: 14px 16px;
font-size: 12px;
font-weight: 600;
color: #64748b;
text-align: left;
border-bottom: 1px solid #e2e8f0;
white-space: nowrap;
}
tbody td {
padding: 16px;
font-size: 14px;
color: #334155;
border-bottom: 1px solid #f1f5f9;
vertical-align: middle;
}
tbody tr:hover { background: #faf5ff; }
tbody tr:last-child td { border-bottom: none; }
/* ── 상품 정보 ── */
.product-name {
font-weight: 600;
color: #1e293b;
margin-bottom: 2px;
}
.product-supplier {
font-size: 12px;
color: #94a3b8;
}
.product-supplier.set {
color: #8b5cf6;
font-weight: 500;
}
/* ── 코드/바코드 ── */
.code {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
padding: 4px 8px;
border-radius: 6px;
display: inline-block;
}
.code-drug {
background: #ede9fe;
color: #6d28d9;
}
.code-barcode {
background: #d1fae5;
color: #065f46;
}
.code-na {
background: #f1f5f9;
color: #94a3b8;
}
/* ── 가격 ── */
.price {
font-weight: 600;
color: #1e293b;
white-space: nowrap;
}
/* ── QR 버튼 ── */
.btn-qr {
background: #8b5cf6;
color: #fff;
border: none;
padding: 8px 14px;
border-radius: 8px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
white-space: nowrap;
}
.btn-qr:hover { background: #7c3aed; }
.btn-qr:active { transform: scale(0.95); }
/* ── 빈 상태 ── */
.empty-state {
text-align: center;
padding: 60px 20px;
color: #94a3b8;
}
.empty-state .icon {
font-size: 48px;
margin-bottom: 16px;
}
.empty-state p {
font-size: 15px;
}
/* ── 모달 ── */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal-overlay.active { display: flex; }
.modal-box {
background: #fff;
border-radius: 16px;
padding: 24px;
max-width: 400px;
width: 90%;
text-align: center;
}
.modal-title {
font-size: 18px;
font-weight: 700;
margin-bottom: 16px;
}
.modal-preview {
margin: 16px 0;
}
.modal-preview img {
max-width: 200px;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
/* ── 수량 선택기 ── */
.qty-selector {
display: flex;
align-items: center;
justify-content: center;
gap: 0;
margin: 20px 0;
}
.qty-btn {
width: 44px;
height: 44px;
border: none;
background: #f1f5f9;
font-size: 24px;
font-weight: 600;
color: #64748b;
cursor: pointer;
transition: all 0.15s;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
}
.qty-btn:first-child { border-radius: 12px 0 0 12px; }
.qty-btn:last-child { border-radius: 0 12px 12px 0; }
.qty-btn:hover { background: #e2e8f0; color: #334155; }
.qty-btn:active { transform: scale(0.95); background: #cbd5e1; }
.qty-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.qty-value {
width: 64px;
height: 44px;
background: #fff;
border: 2px solid #e2e8f0;
border-left: none;
border-right: none;
font-size: 20px;
font-weight: 700;
color: #1e293b;
display: flex;
align-items: center;
justify-content: center;
}
.qty-label {
font-size: 13px;
color: #64748b;
margin-bottom: 8px;
}
.modal-btns {
display: flex;
gap: 12px;
justify-content: center;
margin-top: 20px;
}
.modal-btn {
padding: 10px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
border: none;
transition: all 0.15s;
}
.modal-btn.cancel { background: #f1f5f9; color: #64748b; }
.modal-btn.cancel:hover { background: #e2e8f0; }
.modal-btn.confirm { background: #8b5cf6; color: #fff; }
.modal-btn.confirm:hover { background: #7c3aed; }
/* ── 반응형 ── */
@media (max-width: 768px) {
.search-box { flex-direction: column; }
.table-wrap { overflow-x: auto; }
table { min-width: 700px; }
}
</style>
</head>
<body>
<div class="header">
<div class="header-nav">
<a href="/admin">← 관리자 홈</a>
<div>
<a href="/admin/sales-detail" style="margin-right: 16px;">판매 조회</a>
<a href="/admin/sales">판매 내역</a>
</div>
</div>
<h1>🔍 제품 검색</h1>
<p>전체 제품 검색 · QR 라벨 인쇄</p>
</div>
<div class="content">
<!-- 검색 -->
<div class="search-section">
<div class="search-box">
<input type="text" class="search-input" id="searchInput"
placeholder="상품명, 바코드, 상품코드로 검색..."
onkeypress="if(event.key==='Enter')searchProducts()">
<button class="search-btn" onclick="searchProducts()">🔍 검색</button>
</div>
<div class="search-hint">
<span>예시</span> 타이레놀, 벤포파워, 8806418067510, LB000001423
</div>
</div>
<!-- 결과 -->
<div class="result-count" id="resultCount" style="display:none;">
검색 결과: <strong id="resultNum">0</strong>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>상품명</th>
<th>상품코드</th>
<th>바코드</th>
<th>판매가</th>
<th>QR</th>
</tr>
</thead>
<tbody id="productsTableBody">
<tr>
<td colspan="5" class="empty-state">
<div class="icon">🔍</div>
<p>상품명, 바코드, 상품코드로 검색하세요</p>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- QR 인쇄 모달 -->
<div class="modal-overlay" id="qrModal" onclick="if(event.target===this)closeQRModal()">
<div class="modal-box">
<div class="modal-title">🏷️ QR 라벨 인쇄</div>
<div id="qrInfo" style="margin-bottom:12px;"></div>
<div class="modal-preview" id="qrPreview">
<p style="color:#64748b;">미리보기 로딩 중...</p>
</div>
<div class="qty-label">인쇄 매수</div>
<div class="qty-selector">
<button class="qty-btn" onclick="adjustQty(-1)" id="qtyMinus"></button>
<div class="qty-value" id="qtyValue">1</div>
<button class="qty-btn" onclick="adjustQty(1)" id="qtyPlus">+</button>
</div>
<div class="modal-btns">
<button class="modal-btn cancel" onclick="closeQRModal()">취소</button>
<button class="modal-btn confirm" onclick="confirmPrintQR()" id="printBtn">인쇄</button>
</div>
</div>
</div>
<script>
let productsData = [];
let selectedItem = null;
let printQty = 1;
const MAX_QTY = 10;
const MIN_QTY = 1;
function formatPrice(num) {
if (!num) return '-';
return new Intl.NumberFormat('ko-KR').format(num) + '원';
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
}
function searchProducts() {
const search = document.getElementById('searchInput').value.trim();
if (!search) {
alert('검색어를 입력하세요');
return;
}
if (search.length < 2) {
alert('2글자 이상 입력하세요');
return;
}
const tbody = document.getElementById('productsTableBody');
tbody.innerHTML = '<tr><td colspan="5" class="empty-state"><p>검색 중...</p></td></tr>';
fetch(`/api/products?search=${encodeURIComponent(search)}`)
.then(res => res.json())
.then(data => {
if (data.success) {
productsData = data.items;
document.getElementById('resultCount').style.display = 'block';
document.getElementById('resultNum').textContent = productsData.length;
renderTable();
} else {
tbody.innerHTML = `<tr><td colspan="5" class="empty-state"><p>오류: ${data.error}</p></td></tr>`;
}
})
.catch(err => {
tbody.innerHTML = '<tr><td colspan="5" class="empty-state"><p>검색 실패</p></td></tr>';
});
}
function renderTable() {
const tbody = document.getElementById('productsTableBody');
if (productsData.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="empty-state"><div class="icon">📭</div><p>검색 결과가 없습니다</p></td></tr>';
return;
}
tbody.innerHTML = productsData.map((item, idx) => `
<tr>
<td>
<div class="product-name">${escapeHtml(item.product_name)}</div>
<div class="product-supplier ${item.is_set ? 'set' : ''}">${escapeHtml(item.supplier) || ''}</div>
</td>
<td><span class="code code-drug">${item.drug_code}</span></td>
<td>${item.barcode
? `<span class="code code-barcode">${item.barcode}</span>`
: `<span class="code code-na">없음</span>`}</td>
<td class="price">${formatPrice(item.sale_price)}</td>
<td>
<button class="btn-qr" onclick="printQR(${idx})">🏷️ QR</button>
</td>
</tr>
`).join('');
}
// ── QR 인쇄 관련 ──
function adjustQty(delta) {
printQty = Math.max(MIN_QTY, Math.min(MAX_QTY, printQty + delta));
updateQtyUI();
}
function updateQtyUI() {
document.getElementById('qtyValue').textContent = printQty;
document.getElementById('qtyMinus').disabled = printQty <= MIN_QTY;
document.getElementById('qtyPlus').disabled = printQty >= MAX_QTY;
document.getElementById('printBtn').textContent = printQty > 1 ? `${printQty}장 인쇄` : '인쇄';
}
function printQR(idx) {
selectedItem = productsData[idx];
printQty = 1;
const modal = document.getElementById('qrModal');
const preview = document.getElementById('qrPreview');
const info = document.getElementById('qrInfo');
preview.innerHTML = '<p style="color:#64748b;">미리보기 로딩 중...</p>';
info.innerHTML = `
<strong>${escapeHtml(selectedItem.product_name)}</strong><br>
<span style="color:#64748b;font-size:13px;">
바코드: ${selectedItem.barcode || selectedItem.drug_code || 'N/A'}<br>
가격: ${formatPrice(selectedItem.sale_price)}
</span>
`;
updateQtyUI();
modal.classList.add('active');
fetch('/api/qr-preview', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
drug_name: selectedItem.product_name,
barcode: selectedItem.barcode || '',
drug_code: selectedItem.drug_code || '',
sale_price: selectedItem.sale_price || 0
})
})
.then(res => res.json())
.then(data => {
if (data.success && data.image) {
preview.innerHTML = `<img src="${data.image}" alt="QR 미리보기">`;
} else {
preview.innerHTML = '<p style="color:#ef4444;">미리보기 실패</p>';
}
})
.catch(() => {
preview.innerHTML = '<p style="color:#ef4444;">미리보기 오류</p>';
});
}
function closeQRModal() {
document.getElementById('qrModal').classList.remove('active');
selectedItem = null;
printQty = 1;
}
async function confirmPrintQR() {
if (!selectedItem) return;
const btn = document.getElementById('printBtn');
const totalQty = printQty;
btn.disabled = true;
let successCount = 0;
let errorMsg = '';
for (let i = 0; i < totalQty; i++) {
btn.textContent = `인쇄 중... (${i + 1}/${totalQty})`;
try {
const res = await fetch('/api/qr-print', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
drug_name: selectedItem.product_name,
barcode: selectedItem.barcode || '',
drug_code: selectedItem.drug_code || '',
sale_price: selectedItem.sale_price || 0
})
});
const data = await res.json();
if (data.success) {
successCount++;
} else {
errorMsg = data.error || '알 수 없는 오류';
break;
}
if (i < totalQty - 1) {
await new Promise(r => setTimeout(r, 500));
}
} catch (err) {
errorMsg = err.message;
break;
}
}
btn.disabled = false;
updateQtyUI();
if (successCount === totalQty) {
alert(`✅ QR 라벨 ${totalQty}장 인쇄 완료!`);
closeQRModal();
} else if (successCount > 0) {
alert(`⚠️ ${successCount}/${totalQty}장 인쇄 완료\n오류: ${errorMsg}`);
} else {
alert(`❌ 인쇄 실패: ${errorMsg}`);
}
}
// 페이지 로드 시 검색창 포커스
document.getElementById('searchInput').focus();
</script>
</body>
</html>

View File

@ -261,6 +261,152 @@
color: #64748b;
}
/* ── QR 인쇄 버튼 ── */
.btn-qr {
background: #8b5cf6;
color: #fff;
border: none;
padding: 6px 12px;
border-radius: 6px;
font-size: 11px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
white-space: nowrap;
}
.btn-qr:hover { background: #7c3aed; }
.btn-qr:disabled {
background: #cbd5e1;
cursor: not-allowed;
}
.btn-qr.printing {
background: #f59e0b;
}
/* ── 모달 ── */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal-overlay.active { display: flex; }
.modal-box {
background: #fff;
border-radius: 16px;
padding: 24px;
max-width: 400px;
width: 90%;
text-align: center;
}
.modal-title {
font-size: 18px;
font-weight: 700;
margin-bottom: 16px;
}
.modal-preview {
margin: 16px 0;
}
.modal-preview img {
max-width: 200px;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
/* ── 수량 선택기 ── */
.qty-selector {
display: flex;
align-items: center;
justify-content: center;
gap: 0;
margin: 20px 0;
}
.qty-btn {
width: 44px;
height: 44px;
border: none;
background: #f1f5f9;
font-size: 24px;
font-weight: 600;
color: #64748b;
cursor: pointer;
transition: all 0.15s;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
}
.qty-btn:first-child {
border-radius: 12px 0 0 12px;
}
.qty-btn:last-child {
border-radius: 0 12px 12px 0;
}
.qty-btn:hover {
background: #e2e8f0;
color: #334155;
}
.qty-btn:active {
transform: scale(0.95);
background: #cbd5e1;
}
.qty-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.qty-value {
width: 64px;
height: 44px;
background: #fff;
border: 2px solid #e2e8f0;
border-left: none;
border-right: none;
font-size: 20px;
font-weight: 700;
color: #1e293b;
display: flex;
align-items: center;
justify-content: center;
}
.qty-label {
font-size: 13px;
color: #64748b;
margin-bottom: 8px;
}
.modal-btns {
display: flex;
gap: 12px;
justify-content: center;
margin-top: 20px;
}
.modal-btn {
padding: 10px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
border: none;
transition: all 0.15s;
}
.modal-btn.cancel {
background: #f1f5f9;
color: #64748b;
}
.modal-btn.cancel:hover { background: #e2e8f0; }
.modal-btn.confirm {
background: #8b5cf6;
color: #fff;
}
.modal-btn.confirm:hover { background: #7c3aed; }
.modal-btn.confirm:active { transform: scale(0.98); }
/* ── 반응형 ── */
@media (max-width: 768px) {
.stats-grid { grid-template-columns: repeat(2, 1fr); }
@ -355,10 +501,11 @@
<th>수량</th>
<th>단가</th>
<th>합계</th>
<th>QR</th>
</tr>
</thead>
<tbody id="salesTableBody">
<tr><td colspan="6" class="loading">로딩 중...</td></tr>
<tr><td colspan="7" class="loading">로딩 중...</td></tr>
</tbody>
</table>
</div>
@ -415,11 +562,11 @@
const tbody = document.getElementById('salesTableBody');
if (salesData.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="empty-state">판매 내역이 없습니다</td></tr>';
tbody.innerHTML = '<tr><td colspan="7" class="empty-state">판매 내역이 없습니다</td></tr>';
return;
}
tbody.innerHTML = salesData.map(item => `
tbody.innerHTML = salesData.map((item, idx) => `
<tr>
<td style="white-space:nowrap;font-size:12px;color:#64748b;">${item.sale_date}</td>
<td>
@ -430,6 +577,11 @@
<td class="qty">${item.quantity}</td>
<td class="price">${formatPrice(item.unit_price)}</td>
<td class="price">${formatPrice(item.total_price)}</td>
<td>
<button class="btn-qr" onclick="printQR(${idx})" title="QR 라벨 인쇄">
🏷️ QR
</button>
</td>
</tr>
`).join('');
}
@ -445,7 +597,7 @@
const barcodeFilter = document.getElementById('barcodeFilter').value;
document.getElementById('salesTableBody').innerHTML =
'<tr><td colspan="6" class="loading">로딩 중...</td></tr>';
'<tr><td colspan="7" class="loading">로딩 중...</td></tr>';
fetch(`/api/sales-detail?days=${period}&search=${encodeURIComponent(search)}&barcode=${barcodeFilter}`)
.then(res => res.json())
@ -463,17 +615,164 @@
renderTable();
} else {
document.getElementById('salesTableBody').innerHTML =
`<tr><td colspan="6" class="empty-state">오류: ${data.error}</td></tr>`;
`<tr><td colspan="7" class="empty-state">오류: ${data.error}</td></tr>`;
}
})
.catch(err => {
document.getElementById('salesTableBody').innerHTML =
`<tr><td colspan="6" class="empty-state">데이터 로드 실패</td></tr>`;
`<tr><td colspan="7" class="empty-state">데이터 로드 실패</td></tr>`;
});
}
// QR 인쇄 관련
let selectedItem = null;
let printQty = 1;
const MAX_QTY = 10;
const MIN_QTY = 1;
function adjustQty(delta) {
printQty = Math.max(MIN_QTY, Math.min(MAX_QTY, printQty + delta));
updateQtyUI();
}
function updateQtyUI() {
document.getElementById('qtyValue').textContent = printQty;
document.getElementById('qtyMinus').disabled = printQty <= MIN_QTY;
document.getElementById('qtyPlus').disabled = printQty >= MAX_QTY;
const btn = document.getElementById('printBtn');
btn.textContent = printQty > 1 ? `${printQty}장 인쇄` : '인쇄';
}
function printQR(idx) {
selectedItem = salesData[idx];
printQty = 1;
// 미리보기 요청
const modal = document.getElementById('qrModal');
const preview = document.getElementById('qrPreview');
const info = document.getElementById('qrInfo');
preview.innerHTML = '<p style="color:#64748b;">미리보기 로딩 중...</p>';
info.innerHTML = `
<strong>${escapeHtml(selectedItem.product_name)}</strong><br>
<span style="color:#64748b;font-size:13px;">
바코드: ${selectedItem.barcode || selectedItem.drug_code || 'N/A'}<br>
가격: ${formatPrice(selectedItem.unit_price)}
</span>
`;
updateQtyUI();
modal.classList.add('active');
// 미리보기 이미지 로드
fetch('/api/qr-preview', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
drug_name: selectedItem.product_name,
barcode: selectedItem.barcode || '',
drug_code: selectedItem.drug_code || '',
sale_price: selectedItem.unit_price || 0
})
})
.then(res => res.json())
.then(data => {
if (data.success && data.image) {
preview.innerHTML = `<img src="${data.image}" alt="QR 미리보기">`;
} else {
preview.innerHTML = '<p style="color:#ef4444;">미리보기 실패</p>';
}
})
.catch(err => {
preview.innerHTML = '<p style="color:#ef4444;">미리보기 오류</p>';
});
}
function closeQRModal() {
document.getElementById('qrModal').classList.remove('active');
selectedItem = null;
printQty = 1;
}
async function confirmPrintQR() {
if (!selectedItem) return;
const btn = document.getElementById('printBtn');
const totalQty = printQty;
btn.disabled = true;
let successCount = 0;
let errorMsg = '';
for (let i = 0; i < totalQty; i++) {
btn.textContent = `인쇄 중... (${i + 1}/${totalQty})`;
try {
const res = await fetch('/api/qr-print', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
drug_name: selectedItem.product_name,
barcode: selectedItem.barcode || '',
drug_code: selectedItem.drug_code || '',
sale_price: selectedItem.unit_price || 0
})
});
const data = await res.json();
if (data.success) {
successCount++;
} else {
errorMsg = data.error || '알 수 없는 오류';
break;
}
// 연속 인쇄 시 약간의 딜레이
if (i < totalQty - 1) {
await new Promise(r => setTimeout(r, 500));
}
} catch (err) {
errorMsg = err.message;
break;
}
}
btn.disabled = false;
updateQtyUI();
if (successCount === totalQty) {
alert(`✅ QR 라벨 ${totalQty}장 인쇄 완료!`);
closeQRModal();
} else if (successCount > 0) {
alert(`⚠️ ${successCount}/${totalQty}장 인쇄 완료\n오류: ${errorMsg}`);
} else {
alert(`❌ 인쇄 실패: ${errorMsg}`);
}
}
// 초기 로드
loadSalesData();
</script>
<!-- QR 인쇄 모달 -->
<div class="modal-overlay" id="qrModal" onclick="if(event.target===this)closeQRModal()">
<div class="modal-box">
<div class="modal-title">🏷️ QR 라벨 인쇄</div>
<div id="qrInfo" style="margin-bottom:12px;"></div>
<div class="modal-preview" id="qrPreview">
<p style="color:#64748b;">미리보기 로딩 중...</p>
</div>
<div class="qty-label">인쇄 매수</div>
<div class="qty-selector">
<button class="qty-btn" onclick="adjustQty(-1)" id="qtyMinus"></button>
<div class="qty-value" id="qtyValue">1</div>
<button class="qty-btn" onclick="adjustQty(1)" id="qtyPlus">+</button>
</div>
<div class="modal-btns">
<button class="modal-btn cancel" onclick="closeQRModal()">취소</button>
<button class="modal-btn confirm" onclick="confirmPrintQR()" id="printBtn">인쇄</button>
</div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,324 @@
# AI 업셀링 시스템 아키텍처
> 청춘약국 AI 기반 맞춤 제품 추천 시스템의 전체 구조 및 데이터 흐름
## 개요
고객이 마일리지를 적립할 때, 실시간으로 AI가 추가 구매 추천을 생성하는 시스템.
**핵심 특징:**
- POS(PIT3000) 판매 데이터 기반 추천
- 고객별 구매 이력 분석
- 약국 실제 재고(최근 판매 제품) 기반
- Clawdbot Gateway를 통한 Claude 연동 (추가 API 비용 없음)
---
## 아키텍처 다이어그램
```
┌─────────────────────────────────────────────────────────────────┐
│ 전체 흐름 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ [POS 판매] │
│ │ │
│ ▼ │
│ [MSSQL: PM_PRES] ←─── PIT3000 POS 데이터 │
│ │ │
│ ▼ │
│ [키오스크 적립 요청] POST /api/kiosk/claim │
│ │ │
│ ├──────────────────────────────────────┐ │
│ │ │ │
│ ▼ ▼ │
│ [SQLite: mileage.db] [백그라운드 스레드] │
│ - claim_tokens _generate_upsell_recommendation()
│ - users │ │
│ │ │
│ ┌────────────────────┼────────────────┐ │
│ │ ▼ │ │
│ │ ┌─────────────────────┐ │ │
│ │ │ 데이터 수집 │ │ │
│ │ ├─────────────────────┤ │ │
│ │ │ 1. 현재 구매 품목 │ │ │
│ │ │ 2. 고객 구매 이력 │ │ │
│ │ │ 3. 약국 보유 제품 │ │ │
│ │ └──────────┬──────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌─────────────────────┐ │ │
│ │ │ Clawdbot Gateway │ │ │
│ │ │ (WebSocket) │ │ │
│ │ │ │ │ │
│ │ │ Model: Sonnet │ │ │
│ │ │ (비용 최적화) │ │ │
│ │ └──────────┬──────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌─────────────────────┐ │ │
│ │ │ Claude AI 응답 │ │ │
│ │ │ {product, reason, │ │ │
│ │ │ message} │ │ │
│ │ └──────────┬──────────┘ │ │
│ │ │ │ │
│ └───────────────────┼─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────┐ │
│ │ SQLite: ai_recommendations │
│ │ - recommended_product │ │
│ │ - recommendation_message│ │
│ │ - trigger_products │ │
│ │ - expires_at │ │
│ └──────────┬──────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────┐ │
│ │ 마이페이지 / 키오스크 │ │
│ │ 추천 카드 노출 │ │
│ └─────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## 데이터 흐름 상세
### 1단계: 트리거 (키오스크 적립)
```python
# POST /api/kiosk/claim
# 고객이 전화번호로 마일리지 적립 요청
# 적립 완료 후 백그라운드에서 AI 추천 생성
threading.Thread(target=_bg_upsell, daemon=True).start()
```
**포인트:** 적립 응답은 즉시 반환, AI 추천은 백그라운드에서 처리 (non-blocking)
---
### 2단계: 데이터 수집
#### 2-1. 현재 구매 품목
```python
# 키오스크 트리거 시 전달받은 sale_items에서 추출
current_items = ', '.join(item['name'] for item in sale_items)
# 예: "타이레놀, 판피린, 비타민C"
```
#### 2-2. 고객 구매 이력 (최근 5건)
```sql
-- SQLite: 최근 적립한 거래 ID 조회
SELECT ct.transaction_id
FROM claim_tokens ct
WHERE ct.claimed_by_user_id = ? AND ct.transaction_id != ?
ORDER BY ct.claimed_at DESC LIMIT 5
-- MSSQL: 각 거래의 품목 조회
SELECT ISNULL(G.GoodsName, '') AS goods_name
FROM SALE_SUB S
LEFT JOIN PM_DRUG.dbo.CD_GOODS G ON S.DrugCode = G.DrugCode
WHERE S.SL_NO_order = :tid
```
#### 2-3. 약국 보유 제품 목록 (TOP 40)
```sql
-- MSSQL: 최근 30일 판매 상위 40개 제품
SELECT TOP 40
ISNULL(G.GoodsName, '') AS name,
COUNT(*) as sales,
MAX(G.Saleprice) as price
FROM SALE_SUB S
LEFT JOIN PM_DRUG.dbo.CD_GOODS G ON S.DrugCode = G.DrugCode
WHERE S.SL_DT_appl >= CONVERT(VARCHAR(8), DATEADD(DAY, -30, GETDATE()), 112)
AND G.GoodsName IS NOT NULL
AND G.GoodsName NOT LIKE N'%(판매불가)%'
GROUP BY G.GoodsName
ORDER BY COUNT(*) DESC
```
**왜 TOP 40?**
- AI 컨텍스트 토큰 절약
- 실제로 많이 팔리는 제품만 추천 (재고 있음 보장)
- 판매불가 제품 자동 제외
---
### 3단계: AI 프롬프트 구성
```python
UPSELL_MODEL = 'anthropic/claude-sonnet-4-5' # Opus 대신 Sonnet (비용 최적화)
SYSTEM_PROMPT = """당신은 동네 약국(청춘약국)의 친절한 약사입니다.
고객의 구매 이력을 보고, 약국에 실제로 있는 제품 중에서 하나를 추천합니다.
반드시 [약국 보유 제품 목록]에 있는 제품명을 그대로 사용하세요.
목록에 없는 제품은 절대 추천하지 마세요.
강압적이거나 광고 같은 느낌이 아닌, 진심으로 건강을 걱정하는 약사의 말투로 작성해주세요.
반드시 아래 JSON 형식으로만 응답하세요."""
USER_PROMPT = f"""고객 이름: {user_name}
오늘 구매한 약: {current_items}
최근 구매 이력: {recent_products}
[약국 보유 제품 목록 — 이 중에서만 추천하세요]
{product_list}
규칙:
1. 위 목록에 있는 제품 중 오늘 구매한 약과 함께 먹으면 좋거나, 구매 패턴상 필요해보이는 약 1가지만 추천
2. 오늘 이미 구매한 제품은 추천하지 마세요
3. 메시지는 2문장 이내, 따뜻하고 자연스러운 톤
4. product 필드에는 목록에 있는 제품명을 정확히 그대로 적어주세요
응답 JSON:
{{"product": "목록에 있는 정확한 제품명", "reason": "추천 이유 (내부용)", "message": "고객용 메시지"}}"""
```
---
### 4단계: AI 응답 및 저장
```json
// Claude 응답 예시
{
"product": "종근당 비타민D 1000IU",
"reason": "감기약과 함께 면역력 강화에 도움",
"message": "홍길동님, 감기약 드시면서 비타민D도 같이 챙기시면 회복에 도움이 되실 거예요. 요즘 일조량 적을 때 특히 좋답니다."
}
```
```sql
-- SQLite: ai_recommendations 테이블에 저장
INSERT INTO ai_recommendations
(user_id, transaction_id, recommended_product, recommendation_message,
recommendation_reason, trigger_products, ai_raw_response, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
```
---
### 5단계: 추천 노출
```
GET /api/recommendation/{user_id}
```
- 마이페이지에서 조회
- 키오스크에서 적립 직후 표시
- 7일 후 만료 (expires_at)
---
## 핵심 쿼리 정리
| 용도 | DB | 쿼리 |
|------|-----|------|
| 고객 최근 거래 | SQLite | `claim_tokens WHERE claimed_by_user_id = ?` |
| 거래별 품목 | MSSQL | `SALE_SUB JOIN CD_GOODS WHERE SL_NO_order = ?` |
| 보유 제품 TOP 40 | MSSQL | `SALE_SUB GROUP BY GoodsName ORDER BY COUNT DESC` |
| 추천 저장 | SQLite | `INSERT INTO ai_recommendations` |
| 추천 조회 | SQLite | `SELECT FROM ai_recommendations WHERE user_id = ?` |
---
## 비용 최적화 전략
### 1. 모델 선택
```python
# 업셀링은 Sonnet (빠르고 저렴)
UPSELL_MODEL = 'anthropic/claude-sonnet-4-5'
# 복잡한 분석은 Opus (메인 세션)
# sessions.patch로 세션별 모델 오버라이드
```
### 2. 토큰 절약
- 보유 제품 TOP 40개만 전달 (전체 재고 X)
- 시스템 프롬프트 간결하게
- JSON 응답 강제 (불필요한 설명 제거)
### 3. 세션 분리
```python
# 고객별 세션 분리 → 컨텍스트 축적 방지
session_id = f'upsell-real-{user_name}'
```
---
## Fallback 전략
```python
# 1차 시도: 실데이터 기반 (보유 제품 목록 제공)
rec = generate_upsell_real(user_name, current_items, recent_products, available)
# 2차 시도: 자유 생성 (보유 제품 목록 없이)
if not rec:
rec = generate_upsell(user_name, current_items, recent_products)
```
**왜 Fallback?**
- MSSQL 연결 실패 시에도 추천 가능
- 보유 제품 쿼리 실패해도 서비스 지속
---
## 관련 파일
```
pharmacy-pos-qr-system/
├── backend/
│ ├── app.py
│ │ ├── _get_available_products() # 보유 제품 조회
│ │ ├── _generate_upsell_recommendation() # 메인 로직
│ │ └── /api/recommendation/{user_id} # 추천 조회 API
│ │
│ ├── services/
│ │ └── clawdbot_client.py
│ │ ├── generate_upsell() # 자유 생성
│ │ ├── generate_upsell_real() # 실데이터 기반
│ │ └── ask_clawdbot() # Gateway 호출
│ │
│ ├── templates/
│ │ └── admin_ai_crm.html # CRM 관리 페이지
│ │
│ └── db/
│ └── mileage.db # SQLite (ai_recommendations)
└── docs/
├── ai-upselling-architecture.md # 이 문서
└── clawdbot-gateway-api.md # Gateway 연동 가이드
```
---
## 향후 개선 방향
### 1. 추천 정확도 향상
- 제품 카테고리 분류 추가 (감기약, 영양제, 외용제 등)
- 계절/시간대별 추천 가중치
- 고객 연령대/성별 기반 필터
### 2. 성과 측정
- 추천 → 실제 구매 전환율 추적
- A/B 테스트 (추천 vs 비추천)
- 인기 추천 제품 통계
### 3. 실시간 재고 연동
- 현재: 최근 30일 판매 기준 (간접 재고)
- 개선: 실제 재고 수량 기반 추천
### 4. 멀티 추천
- 현재: 1개 제품만 추천
- 개선: 상황별 2-3개 옵션 제시
---
*작성: 2026-02-27 | 용림 🐉*

View File

@ -0,0 +1,98 @@
.# 팜IT3000 (PIT3000) DB 구조
## DB 접속 정보
- **서버**: 192.168.0.101\PM2014 (MSSQL)
- **계정**: sa / tmddls214!%(
- **ODBC**: Driver 18 + `OPENSSL_CONF=/root/person-lookup-web-local/openssl_legacy.conf` 필수
- **코드 위치**: /root/person-lookup-web-local/ (CT 200)
## 데이터베이스 목록
| DB명 | 용도 |
|------|------|
| PM_BASE | 환자 정보, 개인정보, 판매마스터 |
| PM_PRES | 처방전, 판매(SALE), 수납(CD_SUNAB), 키오스크 |
| PM_DRUG | 약품 마스터(CD_GOODS), 창고 거래(WH_sub) |
| PM_DUMS | 재고 관리(INVENTORY, NIMS_REALTIME_INVENTORY) |
| PM_ALIMI | 알림톡, SMS |
| PM_ALDB | 알림 DB |
| PM_EDIRECE/PM_EDISEND | EDI 전자문서 |
| PM_IMAGE | 약품 이미지 |
| PM_JOBLOG | 작업/시스템 로그 |
## 결제(수납) 테이블 구조
### CD_SUNAB (PM_PRES) - 핵심 수납 테이블
건별 결제 내역. PRESERIAL로 처방과 연결.
#### 결제 수단 구분 (금액 기반, 단일 구분 컬럼 없음)
| 구분 | 카드결제 | 현금결제 | 외상/기타 |
|------|---------|---------|----------|
| 조제(ETC, 전문의약품) | `ETC_CARD` | `ETC_CASH` | `ETC_PAPER` |
| OTC(일반의약품) | `OTC_CARD` | `OTC_CASH` | `OTC_PAPER` |
**판별법**: 금액이 0보다 크면 해당 결제수단 사용
- `ETC_CARD=6100, ETC_CASH=0` → 카드결제
- `ETC_CARD=0, ETC_CASH=5100` → 현금결제
#### 카드 관련 컬럼
| 컬럼 | 설명 |
|------|------|
| `PCardName` | 카드사 이름 (KB국민카드, 신한카드 등) |
| `pAPPROVAL_NUM` | 카드 승인번호 |
| `pCARDINMODE` | 카드 입력 방식 |
| `pTRDTYPE` | 거래 유형 (D1 등) |
| `pCHK_GUBUN` | 체크 구분 (TASA=타사, KIC 등) |
| `Appr_Gubun` | 승인 구분 (9=정상승인, A 등) |
| `pCANCEL_NUM` | 취소 승인번호 |
| `CANCEL_DATE` | 취소 일시 |
#### 현금 관련 컬럼
| 컬럼 | 설명 |
|------|------|
| `nCASHINMODE` | 현금영수증 입력 방식 (1 등, 대부분 빈값=미발행) |
| `nAPPROVAL_NUM` | 현금영수증 승인번호 |
| `nCHK_GUBUN` | 현금 체크 구분 (TASA 등) |
#### 카드사 분포 (PCardName)
| 카드사 | 건수 |
|--------|------|
| KB국민카드 | 6,106 |
| NH농협카드 | 5,172 |
| 비씨카드사 | 4,900 |
| 하나카드 | 4,880 |
| 신한카드 | 3,210 |
| 삼성카드사 | 2,100 |
| 현대카드사 | 1,960 |
| 우리카드 | 1,285 |
| 롯데카드사 | 837 |
| 카카오페이 | 57 |
| 모바일상품권 | 11 |
### CD_SELL_MASTE (PM_BASE) - 판매마스터
| 컬럼 | 설명 |
|------|------|
| `CARD_C` | 카드 결제금액 |
| `CHASH_C` | 현금 결제금액 |
| `PAPER_C` | 외상 금액 |
| `P_GUBUN` | 처방 구분 |
| `C_GUBUN` | 고객 구분 |
### SALE_main (PM_PRES) - 판매 메인
| 컬럼 | 설명 |
|------|------|
| `SL_MY_sale` | 판매금액 |
| `SL_MY_credit` | 외상금액 |
| `SL_MY_recive` | 수납금액 |
| `POS_GUBUN` | POS 구분 (빈값=일반, C=카드?, G=기타?) |
| `PRESERIAL` | 처방번호 (CD_SUNAB과 조인 키) |
### KIOSK 테이블 (PM_PRES)
- `KIOSK_MAIN`: 키오스크 처방 접수
- `KIOSK_CARD`: 키오스크 카드결제 (CARD_NM, CARD_NO, APP_NUM 등)
- `KIOSK_CARD_PRES`: 키오스크 카드-처방 연결
- `KIOSK_SUB`: 키오스크 서브
## 주요 조인 관계
- `CD_SUNAB.PRESERIAL``SALE_main.PRESERIAL` (수납-판매 연결)
- `CD_SUNAB.CUSCODE``CD_PERSON.CUSCODE` (수납-환자 연결, PM_BASE)
- `SALE_main.SL_NO_order``SALE_sub.SL_NO_order` (판매 메인-서브)