Files
dbx-corm/main.py
T
king 7046a504a1 fix: 코드 점검 — 시간대·외부 API·XSS·서버 블로킹 수정
- 네이버/카페24/발주 파일명/반품 입고일을 KST로 고정 (컨테이너 UTC 대응)
- 네이버 API timeout 추가, last-changed-statuses 'more' 페이지 이어서 조회, 주문번호 중복 제거
- 스마트스토어 발주확인을 엑셀 생성 이후로 이동
- 반품 신청/입고 목록 innerHTML 이스케이프 (XSS)
- 카페24 OAuth 콜백: 반사형 XSS 차단, /corm 경로로 복귀
- 블로킹 async 엔드포인트를 sync로 전환 (코드표·반품·송장 업로드·자사몰 행사·밀크런·CS 가져오기)
- DB 연결 closing 처리, 세트 목록 N+1 쿼리 제거
- 반품 일괄 입고 중복 송장 건너뛰기 및 안내
- 작업 결과 메모리 1시간 TTL, 401 로그인 next 경로 중복 수정
- 송장 '.0' 처리 수정 및 네이버/카페24 송장 파싱 공용화
- SortableJS 1.15.6 고정, 중복 코드·미사용 import 정리

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:30:26 +09:00

2015 lines
78 KiB
Python

import os
import sys
import psycopg2
import psycopg2.extras
import time
import json
import re
import io
import datetime
import functools
import urllib.request
import urllib.parse
import uuid
import secrets
import threading
from contextlib import closing
from urllib.parse import quote
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, UploadFile, File, Form, Query, BackgroundTasks
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, RedirectResponse
from erp_auth import AuthGuardMiddleware
import pandas as pd
# Load local settings before application modules read environment values.
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
from naver_api import get_access_token, get_payment_done_orders, get_product_order_details, dispatch_orders, confirm_orders, get_product_details
import cafe24_api
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.concurrency import run_in_threadpool
from pydantic import BaseModel
from typing import List, Optional, Dict
from google_runtime import (
GOOGLE_READ_TIMEOUT, GoogleTimeoutSession, SettingsCache,
create_google_client, google_worker, history_access as google_history_access, run_google_io, settings_update,
)
from settings_store import (
PostgresSettingsStore, SettingsConflict, SettingsNotInitialized,
config_to_rows, rows_to_config, settings_db_config,
)
from history_store import PostgresHistoryStore
from manual_orders import ManualOrderStore, CellConflict
# ==========================================
# SSO / 서브경로 호스팅 설정
# ==========================================
APP_ROOT_PATH = os.getenv("APP_ROOT_PATH", "").rstrip("/")
MAIN_LOGIN_URL = os.getenv("MAIN_LOGIN_URL", "https://dbx.no1king.freeddns.org/login")
MAIN_LOGOUT_URL = os.getenv("MAIN_LOGOUT_URL", "https://dbx.no1king.freeddns.org/logout")
# ==========================================
# 데이터베이스 접속 설정 (환경변수 기반)
# ==========================================
_PG_HOST = os.getenv('POSTGRES_HOST', 'postgres-db')
_PG_PORT = int(os.getenv('POSTGRES_PORT', '5432'))
_PG_USER = os.getenv('POSTGRES_USER', 'king')
_PG_PASSWORD = os.getenv('POSTGRES_PASSWORD', '')
# 1. 메인 프로그램용 DB (품목코드)
DB_CONFIG = {
'host': _PG_HOST,
'port': _PG_PORT,
'dbname': os.getenv('ITEMCODE_DB', 'itemcode_db'),
'user': _PG_USER,
'password': _PG_PASSWORD,
}
SETTINGS_BACKEND = os.getenv("SETTINGS_BACKEND", "google").strip().lower()
if SETTINGS_BACKEND not in {"google", "postgres"}:
raise RuntimeError("SETTINGS_BACKEND는 google 또는 postgres여야 합니다.")
SETTINGS_DB_CONFIG = settings_db_config()
_postgres_settings = PostgresSettingsStore(SETTINGS_DB_CONFIG)
HISTORY_BACKEND = os.getenv("HISTORY_BACKEND", "google").strip().lower()
if HISTORY_BACKEND not in {"google", "postgres"}:
raise RuntimeError("HISTORY_BACKEND는 google 또는 postgres여야 합니다.")
_postgres_history = PostgresHistoryStore(SETTINGS_DB_CONFIG)
MANUAL_ORDERS_BACKEND = os.getenv("MANUAL_ORDERS_BACKEND", "google").strip().lower()
if MANUAL_ORDERS_BACKEND not in {"google", "postgres"}:
raise RuntimeError("MANUAL_ORDERS_BACKEND는 google 또는 postgres여야 합니다.")
if MANUAL_ORDERS_BACKEND == "postgres" and HISTORY_BACKEND != "postgres":
raise RuntimeError("DB 수동발주는 HISTORY_BACKEND=postgres가 필요합니다.")
_manual_orders = ManualOrderStore(SETTINGS_DB_CONFIG)
# 2. 반품 데이터 저장용 DB
RETURN_DB_CONFIG = {
'host': _PG_HOST,
'port': _PG_PORT,
'dbname': os.getenv('RETURN_DB', 'return_db'),
'user': _PG_USER,
'password': _PG_PASSWORD,
}
# 주문정보 조회용 DB(orderlist_db)는 routers/returns.py 에서 사용한다.
# ==========================================
# Google Sheets
try:
import gspread
from google.oauth2.service_account import Credentials
except ImportError:
gspread = None
Credentials = None
app = FastAPI(title="CS Web Program")
# 세션 발급/검증/갱신은 ERP만 수행한다. CORM은 쿠키를 ERP에 전달할 뿐
# 세션 서명 키를 갖거나 Set-Cookie로 ERP 세션을 갱신하지 않는다.
app.add_middleware(AuthGuardMiddleware)
@app.get("/health/db")
def health_db():
"""DB ping — 인증 불필요. dbx-main 의 헬스 배지가 이 경로를 폴링한다."""
try:
conn = psycopg2.connect(**DB_CONFIG, connect_timeout=3)
conn.close()
return JSONResponse({"ok": True, "detail": "ok"})
except Exception as e:
return JSONResponse({"ok": False, "detail": str(e)}, status_code=503)
@app.get("/login")
async def corm_login(request: Request, next: Optional[str] = None):
"""OMS 와 동일 패턴 — 자체 OAuth 없음. dbx-main 으로 위임."""
root = APP_ROOT_PATH
fallback = f"{root}/" if root else "/"
safe = next if (next and next.startswith("/") and not next.startswith("//") and not next.startswith("/\\")) else fallback
sep = "&" if "?" in MAIN_LOGIN_URL else "?"
target = f"{MAIN_LOGIN_URL}{sep}next={quote(safe, safe='/')}"
return RedirectResponse(url=target, status_code=302)
@app.get("/logout")
async def corm_logout():
"""전적으로 dbx-main 에 위임. CORM 은 세션을 직접 만지지 않는다 (쿠키 path 분리 방지)."""
return RedirectResponse(url=MAIN_LOGOUT_URL, status_code=302)
from routers.returns import router as returns_router
app.include_router(returns_router)
from routers.coupang_milkrun import router as coupang_milkrun_router, invalidate_code_map_cache as invalidate_milkrun_code_cache
app.include_router(coupang_milkrun_router)
from routers.mall_event import router as mall_event_router
app.include_router(mall_event_router)
from routers.cs_records import router as cs_records_router, add_special_order_records
app.include_router(cs_records_router)
# Ensure directories exist
os.makedirs("static/css", exist_ok=True)
os.makedirs("static/js", exist_ok=True)
os.makedirs("templates", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
# Globals
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SMS_HISTORY_FILE = os.getenv('SMS_HISTORY_FILE', os.path.join(BASE_DIR, 'sms_history.dat'))
GSPREAD_CRED_FILE = os.getenv('GSPREAD_CRED_FILE', os.path.join(BASE_DIR, 'manual-ordering.json'))
GSPREAD_CRED_JSON = os.getenv('GSPREAD_CRED_JSON', '')
MANUAL_SPREADSHEET_ID = os.getenv('MANUAL_SPREADSHEET_ID', '1QxFtjDurPPZd8NmtXBy4XEUIzkf93aXD5Mlx5kB33xw')
SETTINGS_SPREADSHEET_ID = os.getenv('SETTINGS_SPREADSHEET_ID', '1k7SNEdIaRtGXzQNdJSQAiNSDRwzOePDRTLHY_mNCO8M')
MANUAL_HISTORY_FILE = os.getenv('MANUAL_HISTORY_FILE', os.path.join(BASE_DIR, 'manual_history.dat'))
SMS_HISTORY_HEADERS = ["일시", "주문유형", "입금액", "주문아이템", "메시지 내용", "이름", "연락처", "주소"]
_settings_cache = SettingsCache(
os.getenv("SETTINGS_CACHE_FILE", os.path.join(BASE_DIR, ".cache", "settings.json")),
SETTINGS_SPREADSHEET_ID,
ttl=float(os.getenv("SETTINGS_CACHE_TTL", "60")),
)
# 컨테이너 TZ(기본 UTC)와 무관하게 업무 날짜·파일명은 한국 시간으로 계산한다.
KST = datetime.timezone(datetime.timedelta(hours=9))
WEEKDAYS_KR = ["월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"]
def now_kst():
return datetime.datetime.now(KST)
def env_bool(name: str, default: bool = False) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "y", "on"}
def first_nonempty(data: dict, *keys: str) -> str:
for key in keys:
value = data.get(key)
if value is not None and str(value).strip():
return str(value)
return ""
def load_service_account_credentials(scopes):
if Credentials is None:
raise Exception("google-auth is not installed.")
if GSPREAD_CRED_JSON:
try:
info = json.loads(GSPREAD_CRED_JSON)
return Credentials.from_service_account_info(info, scopes=scopes)
except json.JSONDecodeError as e:
raise Exception("GSPREAD_CRED_JSON is not valid JSON.") from e
if os.path.exists(GSPREAD_CRED_FILE):
return Credentials.from_service_account_file(GSPREAD_CRED_FILE, scopes=scopes)
raise Exception(
f"Google service account key not found. "
f"Set GSPREAD_CRED_JSON or put key file at: {GSPREAD_CRED_FILE}"
)
# ----- Utility Functions -----
def _load_settings_rows():
return get_settings_worksheet().get_all_values()
def settings_worker(function):
"""DB settings must remain available even when Google workers are saturated."""
@functools.wraps(function)
async def wrapped(*args, **kwargs):
if SETTINGS_BACKEND == "postgres":
return await run_in_threadpool(function, *args, **kwargs)
return await run_google_io(function, *args, **kwargs)
return wrapped
def history_worker(function):
@functools.wraps(function)
async def wrapped(*args, **kwargs):
if HISTORY_BACKEND == "postgres":
return await run_in_threadpool(function, *args, **kwargs)
return await run_google_io(function, *args, **kwargs)
return wrapped
def history_access(function):
legacy = google_history_access(function)
@functools.wraps(function)
def wrapped(*args, **kwargs):
# DB records use stable IDs and DB transactions, so a slow Google order
# cancellation must not hold up unrelated history reads and saves.
if HISTORY_BACKEND == "postgres":
return function(*args, **kwargs)
return legacy(*args, **kwargs)
return wrapped
def history_db_call(method, *args, **kwargs):
try:
return getattr(_postgres_history, method)(*args, **kwargs)
except ValueError as exc:
raise HTTPException(status_code=400, detail="내역의 일시와 입력 내용을 확인해주세요.") from exc
except Exception as exc:
raise HTTPException(status_code=503, detail="DB 내역 처리를 확인하지 못했습니다. 새로고침하여 확인해주세요.") from exc
def manual_worker(function):
@functools.wraps(function)
async def wrapped(*args, **kwargs):
if MANUAL_ORDERS_BACKEND == "postgres":
return await run_in_threadpool(function, *args, **kwargs)
return await run_google_io(function, *args, **kwargs)
return wrapped
def manual_db_call(method, *args, **kwargs):
try:
return getattr(_manual_orders, method)(*args, **kwargs)
except CellConflict as exc:
raise HTTPException(status_code=409, detail={"message": str(exc), "conflicts": exc.rows}) from exc
except LookupError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail="수동발주 저장을 확인하지 못했습니다. 입력을 보존한 후 다시 시도해주세요.") from exc
def read_config(force_refresh=False):
if SETTINGS_BACKEND == "postgres":
try:
rows, version = _postgres_settings.read()
config = rows_to_config(rows)
config._settings_version = version
return config
except SettingsNotInitialized as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=503, detail="DB에서 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.") from exc
try:
rows = _settings_cache.read(_load_settings_rows, force=force_refresh)
except Exception as exc:
raise HTTPException(
status_code=503,
detail="구글에서 최신 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.",
) from exc
return rows_to_config(rows)
def write_config(config):
rows = config_to_rows(config)
if SETTINGS_BACKEND == "postgres":
try:
config._settings_version = _postgres_settings.write(
rows, getattr(config, "_settings_version", None),
)
except SettingsConflict as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(
status_code=503,
detail="DB 설정 저장을 확인하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.",
) from exc
return
try:
ws = get_settings_worksheet()
requests = []
column_count = max(len(row) for row in rows)
if len(rows) > ws.row_count or column_count > ws.col_count:
requests.append({"updateSheetProperties": {
"properties": {"sheetId": ws.id, "gridProperties": {
"rowCount": max(len(rows), ws.row_count),
"columnCount": max(column_count, ws.col_count),
}},
"fields": "gridProperties(rowCount,columnCount)",
}})
# One atomic request replaces values and clears old trailing cells. A
# timeout between separate clear/update requests must not erase settings.
requests.append({"updateCells": {
"range": {"sheetId": ws.id},
"rows": [{"values": [
{"userEnteredValue": {"stringValue": str(cell)}} for cell in row
]} for row in rows],
"fields": "userEnteredValue",
}})
ws.spreadsheet.batch_update({"requests": requests})
except Exception as exc:
_settings_cache.invalidate()
raise HTTPException(
status_code=503,
detail="설정 저장 응답을 확인하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.",
) from exc
_settings_cache.publish(rows)
# ----- API Endpoints -----
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
try:
with open("version_history.json", "r", encoding="utf-8") as f:
version_history = json.load(f)
except Exception as e:
print("버전 히스토리 로드 실패:", e)
version_history = []
return templates.TemplateResponse(
request=request,
name="index.html",
context={
"version_history": version_history,
"root_path": APP_ROOT_PATH,
"user_email": getattr(request.state, "erp_user", {}).get("email", ""),
"user_name": getattr(request.state, "erp_user", {}).get("name", ""),
"manual_orders_backend": MANUAL_ORDERS_BACKEND,
}
)
@app.get("/api/config")
async def get_config():
if SETTINGS_BACKEND == "postgres":
config = await run_in_threadpool(read_config)
elif _settings_cache.has_value:
config = read_config()
else:
config = await run_google_io(read_config)
data = {}
for section in config.sections():
data[section] = dict(config.items(section))
data[section]["__order"] = list(config.options(section))
return JSONResponse(data, headers={
"X-Settings-Cache": "none" if SETTINGS_BACKEND == "postgres" else ("stale" if _settings_cache.stale else "fresh"),
"X-Settings-Backend": SETTINGS_BACKEND,
})
class ProductGroup(BaseModel):
old_code: str
new_code: str
name: str
class ProductItem(BaseModel):
is_separator: bool = False
code: str = ""
name: str = ""
label: str = ""
price: int = 0
dprice: int = 0
color: str = ""
is_free: bool = False
class ProductsPayload(BaseModel):
groups: List[ProductGroup]
products: Dict[str, List[ProductItem]]
class SubgroupNamePayload(BaseModel):
group_key: str
subgroup_index: int
name: str = ""
@app.post("/api/products/settings")
@settings_worker
@settings_update
def save_products_settings(payload: ProductsPayload):
config = read_config(force_refresh=True)
if config.has_section("GROUP_NAMES"):
config.remove_section("GROUP_NAMES")
config.add_section("GROUP_NAMES")
for g in payload.groups:
config.set("GROUP_NAMES", g.new_code, g.name)
for g in payload.groups:
if config.has_section(g.old_code):
config.remove_section(g.old_code)
if config.has_section(g.new_code):
config.remove_section(g.new_code)
for g in payload.groups:
config.add_section(g.new_code)
items = payload.products.get(g.new_code, [])
sep_idx = 1
for item in items:
if item.is_separator:
config.set(g.new_code, f"---separator_{sep_idx}---", "")
sep_idx += 1
else:
key = f"*{item.label}{item.color}" if item.is_free else f"{item.label}{item.color}"
val_parts = [item.code, item.name]
if item.price > 0 or item.dprice > 0:
val_parts.append(str(item.price))
if item.dprice > 0:
val_parts.append(str(item.dprice))
val = " | ".join(val_parts)
config.set(g.new_code, key, val)
write_config(config)
return {"status": "success"}
@app.post("/api/products/subgroup-name")
@settings_worker
@settings_update
def save_product_subgroup_name(payload: SubgroupNamePayload):
group_key = payload.group_key.strip()
subgroup_index = payload.subgroup_index
subgroup_name = payload.name.strip()
if not group_key or subgroup_index < 0:
raise HTTPException(status_code=400, detail="잘못된 상품 그룹 정보입니다.")
if len(subgroup_name) > 40:
raise HTTPException(status_code=400, detail="그룹 이름은 40자 이내로 입력해주세요.")
config = read_config(force_refresh=True)
if not config.has_section(group_key):
raise HTTPException(status_code=404, detail="상품 분류를 찾을 수 없습니다.")
if not config.has_section("SUBGROUP_NAMES"):
config.add_section("SUBGROUP_NAMES")
setting_key = f"{group_key}__{subgroup_index}"
if subgroup_name:
config.set("SUBGROUP_NAMES", setting_key, subgroup_name)
else:
config.remove_option("SUBGROUP_NAMES", setting_key)
write_config(config)
return {"status": "success", "name": subgroup_name}
class OrderItem(BaseModel):
code: str
name: str
quantity: int
label: str
item_type: str
class OrderPayload(BaseModel):
customer_name: str
address: str
phone: str
comment: str
order_type: str # e.g., 'noolak', 'pason', 'bullyang', 'misdelivery', 'ellen', 'mira', 'normal'
no_lid: bool
items: List[OrderItem]
is_ellen: bool = False
total_amount: int = 0
def get_current_time_info():
now = now_kst()
time_str = "오후" if now.hour >= 12 else "오전"
day_name = WEEKDAYS_KR[now.weekday()]
date_str = now.strftime(f"%m월 %d일 ({day_name})")
datetime_str = now.strftime(f"%Y-%m-%d %H:%M:%S ({day_name})")
return date_str, time_str, datetime_str
def format_phone_number(num_str):
digits = re.sub(r'\D', '', num_str)
if len(digits) == 10: return f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"
elif len(digits) == 11: return f"{digits[:3]}-{digits[3:7]}-{digits[7:]}"
elif len(digits) >= 8: return f"{digits[:4]}-{digits[4:]}"
return num_str
# Each Google worker owns its requests session and worksheet handles.
_google_state = threading.local()
def get_gspread_client():
if gspread is None:
raise Exception("gspread 라이브러리가 없습니다.")
if getattr(_google_state, "client", None) is None:
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds = load_service_account_credentials(scopes)
_google_state.client = create_google_client(creds)
return _google_state.client
def get_manual_worksheet():
worksheet_manual_global = getattr(_google_state, 'manual', None)
if worksheet_manual_global is None:
client = get_gspread_client()
ss = client.open_by_key(MANUAL_SPREADSHEET_ID)
ws = ss.get_worksheet(0)
if ws.title == "시트1":
try:
ws.update_title("수동 발주")
except Exception:
pass
worksheet_manual_global = ws
_google_state.manual = worksheet_manual_global
return worksheet_manual_global
def get_settings_worksheet():
worksheet_settings_global = getattr(_google_state, 'settings', None)
if worksheet_settings_global is None:
client = get_gspread_client()
ss = client.open_by_key(SETTINGS_SPREADSHEET_ID)
try:
worksheet_settings_global = ss.worksheet("설정")
except gspread.exceptions.WorksheetNotFound:
worksheet_settings_global = ss.add_worksheet(title="설정", rows=500, cols=3)
_google_state.settings = worksheet_settings_global
return worksheet_settings_global
def get_sms_history_worksheet():
worksheet_sms_history_global = getattr(_google_state, 'sms_history', None)
if worksheet_sms_history_global is None:
client = get_gspread_client()
ss = client.open_by_key(SETTINGS_SPREADSHEET_ID)
try:
worksheet_sms_history_global = ss.worksheet("문자내역")
except gspread.exceptions.WorksheetNotFound:
worksheet_sms_history_global = ss.add_worksheet(title="문자내역", rows=1000, cols=10)
if worksheet_sms_history_global.col_count < len(SMS_HISTORY_HEADERS):
worksheet_sms_history_global.add_cols(len(SMS_HISTORY_HEADERS) - worksheet_sms_history_global.col_count)
if worksheet_sms_history_global.row_values(1)[:len(SMS_HISTORY_HEADERS)] != SMS_HISTORY_HEADERS:
worksheet_sms_history_global.update(values=[SMS_HISTORY_HEADERS], range_name="A1:H1", value_input_option='USER_ENTERED')
_google_state.sms_history = worksheet_sms_history_global
return worksheet_sms_history_global
def get_manual_history_worksheet():
worksheet_manual_history_global = getattr(_google_state, 'manual_history', None)
if worksheet_manual_history_global is None:
client = get_gspread_client()
ss = client.open_by_key(SETTINGS_SPREADSHEET_ID)
try:
worksheet_manual_history_global = ss.worksheet("수동발주내역")
except gspread.exceptions.WorksheetNotFound:
worksheet_manual_history_global = ss.add_worksheet(title="수동발주내역", rows=1000, cols=3)
worksheet_manual_history_global.append_row(["일시", "고객명", "주문금액"])
_google_state.manual_history = worksheet_manual_history_global
return worksheet_manual_history_global
@app.on_event("startup")
async def startup_event():
skip_db_init = env_bool("SKIP_DB_INIT", False)
continue_without_db = env_bool("CONTINUE_WITHOUT_DB", False)
if skip_db_init:
print("SKIP_DB_INIT=1 이므로 DB 초기화를 건너뜁니다.")
else:
try:
init_db()
except Exception as e:
if continue_without_db:
print(f"[Warning] DB 초기화 실패. CONTINUE_WITHOUT_DB=1 이므로 서버는 계속 시작합니다: {e}")
else:
raise
if SETTINGS_BACKEND == "postgres":
# Fail visibly on incomplete migration instead of falling back to old sheet values.
await run_in_threadpool(_postgres_settings.read)
elif env_bool("SKIP_GOOGLE_INIT", False):
print("SKIP_GOOGLE_INIT=1 이므로 구글 시트 선초기화를 건너뜁니다.")
else:
# Google unavailability must not delay startup or the DB-backed tabs.
_settings_cache.refresh_in_background(_load_settings_rows)
if HISTORY_BACKEND == "postgres":
await run_in_threadpool(_postgres_history.check_ready)
if MANUAL_ORDERS_BACKEND == "postgres":
await run_in_threadpool(_manual_orders.check_ready)
@app.post("/api/order/submit")
@manual_worker
def submit_order_submit(payload: OrderPayload):
date_str, time_str, current_datetime_str = get_current_time_info()
c_tel = format_phone_number(payload.phone)
order_status_map = {'noolak': '누락', 'pason': '파손', 'bullyang': '불량', 'misdelivery': '오배송'}
order_status = order_status_map.get(payload.order_type, "")
if payload.is_ellen:
title = "수동발주(엘렌)"
else:
title = "수동발주"
if not payload.customer_name:
title = "재구매"
try:
rows = []
lines = []
for i, item in enumerate(payload.items):
lid_suffix = "(뚜껑 없이 통만)" if payload.no_lid and item.item_type == "ORDER_SINGLE" else ""
status_prefix = f", {order_status}" if order_status else ""
sub_text = f"{title}{status_prefix}, {item.name}{lid_suffix} {item.quantity}개{' 발송' if lid_suffix else ''}"
clipboard_status_suffix = f", {order_status}" if order_status else ""
lines.append(f"{payload.customer_name} 고객님 {item.name}{lid_suffix} {item.quantity}개 발송{clipboard_status_suffix}")
c_comment = payload.comment or "빠른배송 부탁드립니다."
c_amount = payload.total_amount if i == len(payload.items) - 1 else ""
row_data = [current_datetime_str, "", c_amount, payload.customer_name, item.code, item.name, item.quantity, payload.address, "", c_tel, c_tel, c_comment, "", title, sub_text]
rows.append(row_data)
if rows:
if MANUAL_ORDERS_BACKEND == "postgres":
manual_db_call("append", rows, {"timestamp": current_datetime_str,
"customer_name": payload.customer_name,
"total_amount": order_status or payload.total_amount})
else:
get_manual_worksheet().append_rows(rows, value_input_option='USER_ENTERED')
clipboard_text = "\r\n".join(lines) + "\r\n"
cs_record_saved_count = 0
cs_record_warning = ""
if order_status and lines:
try:
cs_record_saved_count = add_special_order_records(now_kst().date(), lines, str(uuid.uuid4()))
except Exception as cs_record_error:
cs_record_warning = "발주 입력은 완료됐지만 CS 기록 자동 저장에 실패했습니다."
print(f"CS 기록 자동 저장 실패: {cs_record_error}")
return {
"status": "success",
"message": f"{len(rows)}개 항목 발주 입력 및 클립보드 준비 완료.",
"history_saved": MANUAL_ORDERS_BACKEND == "postgres",
"clipboard_text": clipboard_text,
"timestamp": current_datetime_str,
"cs_record_saved_count": cs_record_saved_count,
"cs_record_warning": cs_record_warning,
}
except HTTPException:
raise
except Exception as e:
err_str = str(e)
if not err_str or err_str.strip() == "{}":
err_str = repr(e)
raise HTTPException(status_code=500, detail=f"수동발주 시트 접근 에러 (스프레드시트에 이메일 편집 권한을 추가했는지 확인해주세요!): {err_str}")
def manual_file_response(content, filename, export_id=None):
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"}
if export_id:
headers["X-Manual-Export-ID"] = export_id
return StreamingResponse(io.BytesIO(content),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers=headers)
class ManualCellChange(BaseModel):
id: int
column: int
value: str
previous_value: str
class ManualCellChanges(BaseModel):
changes: List[ManualCellChange]
class ManualRowVersion(BaseModel):
id: int
version: int
class ManualRowsToArchive(BaseModel):
rows: List[ManualRowVersion]
def require_manual_db():
if MANUAL_ORDERS_BACKEND != "postgres":
raise HTTPException(status_code=409, detail="수동발주 DB 이전 후 사용할 수 있습니다.")
@app.get("/api/manual/orders")
def get_manual_orders():
require_manual_db()
return manual_db_call("list_rows")
@app.post("/api/manual/orders")
def add_manual_order_row():
require_manual_db()
manual_db_call("append", [[get_current_time_info()[2]] + [""] * 14])
return {"status": "success"}
@app.patch("/api/manual/orders/cells")
def patch_manual_order_cells(payload: ManualCellChanges):
require_manual_db()
return {"rows": manual_db_call("patch_cells", [dict(change) for change in payload.changes])}
@app.post("/api/manual/orders/archive")
def archive_manual_order_rows(payload: ManualRowsToArchive):
require_manual_db()
if not payload.rows or len(payload.rows) > 2000:
raise HTTPException(status_code=400, detail="삭제할 행을 선택해주세요.")
manual_db_call("archive_rows", [dict(row) for row in payload.rows])
return {"status": "success"}
@app.get("/api/manual/orders/exports")
def get_manual_exports():
require_manual_db()
return manual_db_call("exports")
@app.get("/api/manual/orders/exports/{export_id}")
def get_manual_export(export_id: uuid.UUID):
require_manual_db()
filename, content = manual_db_call("exports", str(export_id))
return manual_file_response(content, filename)
@app.post("/api/sheet/download_and_clear")
@manual_worker
def download_and_clear_sheet():
now = now_kst()
filename = f"{now:%m}월 {now:%d}일 ({WEEKDAYS_KR[now.weekday()]}) 5 수동발주.xlsx"
if MANUAL_ORDERS_BACKEND == "postgres":
content, export_id = manual_db_call("export_and_archive", filename)
return manual_file_response(content, filename, export_id)
try:
scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
creds = load_service_account_credentials(scopes)
import google.auth.transport.requests
request = google.auth.transport.requests.Request(session=GoogleTimeoutSession())
creds.refresh(request)
access_token = creds.token
worksheet = get_manual_worksheet()
url = f"https://docs.google.com/spreadsheets/export?id={MANUAL_SPREADSHEET_ID}&exportFormat=xlsx"
req = urllib.request.Request(url, headers={"Authorization": f"Bearer {access_token}"})
with urllib.request.urlopen(req, timeout=GOOGLE_READ_TIMEOUT) as response:
content = response.read()
# Clear sheet values instantly
worksheet.batch_clear(["A2:Z10000"])
# Clear formatting (colors, borders, etc) from row 2 downwards
body = {
"requests": [
{
"updateCells": {
"range": {
"sheetId": worksheet.id,
"startRowIndex": 1
},
"fields": "userEnteredFormat"
}
}
]
}
worksheet.spreadsheet.batch_update(body)
return manual_file_response(content, filename)
except Exception as e:
err_str = str(e)
if not err_str or err_str.strip() == "{}":
err_str = repr(e)
raise HTTPException(status_code=500, detail=f"저장 및 삭제 실패: {err_str}")
def _read_jsonl(path):
"""로컬 내역 파일(한 줄당 JSON 하나)을 읽는다. 깨진 줄은 건너뛴다."""
entries = []
if not os.path.exists(path):
return entries
with open(path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
entries.append(json.loads(line))
except ValueError:
pass
return entries
def _write_jsonl(path, entries):
with open(path, 'w', encoding='utf-8') as f:
for entry in entries:
json.dump(entry, f, ensure_ascii=False)
f.write('\n')
@app.get("/api/sms/history")
@history_worker
@history_access
def get_history():
if HISTORY_BACKEND == "postgres":
return history_db_call("list_records", "sms")
local_entries = _read_jsonl(SMS_HISTORY_FILE)
local_history = {item["timestamp"]: item for item in local_entries if "timestamp" in item}
def merge_history_item(sheet_item, local_item):
if not local_item:
return sheet_item
merged = dict(sheet_item)
merged.update(local_item)
for key in ("custName", "custPhone", "custAddress", "customer_name", "phone", "address"):
if not merged.get(key) and sheet_item.get(key):
merged[key] = sheet_item[key]
return merged
history = []
try:
ws = get_sms_history_worksheet()
rows = ws.get_all_values()
if rows and len(rows) > 1:
for row in rows[1:]:
if not row or not row[0].strip():
continue
timestamp = row[0]
order_type = row[1] if len(row) > 1 else ""
deposit_amt = row[2] if len(row) > 2 else ""
items_str = row[3] if len(row) > 3 else ""
preview_text = row[4] if len(row) > 4 else ""
cust_name = row[5] if len(row) > 5 else ""
cust_phone = row[6] if len(row) > 6 else ""
cust_address = row[7] if len(row) > 7 else ""
preview_text = preview_text.replace(" ", "\n")
sheet_item = {
"timestamp": timestamp,
"orderType": order_type,
"deposit_amount_str": deposit_amt,
"items_str": items_str,
"previewText": preview_text,
"custName": cust_name,
"custPhone": cust_phone,
"custAddress": cust_address,
"customer_name": cust_name,
"phone": cust_phone,
"address": cust_address
}
history.append(merge_history_item(sheet_item, local_history.get(timestamp)))
return history
except Exception as e:
print(f"구글 시트에서 기록을 읽어오는 중 에러: {e}")
return local_entries
@app.post("/api/sms/history")
@history_worker
@history_access
def add_history(data: dict):
if HISTORY_BACKEND == "postgres":
return {"status": "success", "id": history_db_call("add", "sms", data)}
with open(SMS_HISTORY_FILE, 'a', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
f.write('\n')
# 구글 시트에 기록
try:
ws = get_sms_history_worksheet()
# 주문 품목 텍스트화
items_str = ""
items = data.get("items", [])
if items:
items_str = ", ".join([f"{i.get('label', '')}[{i.get('code', '')}] {i.get('qty', 0)}개" for i in items])
# 행 높이가 길어지지 않도록 줄바꿈을 띄어쓰기로 변경
preview_text = data.get("previewText", "").replace("\n", " ").replace("\r", "")
customer_name = first_nonempty(data, "custName", "customer_name", "customerName", "name")
customer_phone = first_nonempty(data, "custPhone", "phone", "customer_phone", "customerPhone")
customer_address = first_nonempty(data, "custAddress", "address", "customer_address", "customerAddress")
row = [
data.get("timestamp", ""),
data.get("orderType", ""),
data.get("deposit_amount_str", ""),
items_str,
preview_text,
customer_name,
customer_phone,
customer_address
]
next_row = len(ws.col_values(1)) + 1
ws.update(values=[row], range_name=f"A{next_row}:H{next_row}", value_input_option='USER_ENTERED')
except Exception as e:
print(f"구글 시트 문자내역 기록 실패: {e}")
return {"status": "success"}
@app.delete("/api/sms/history")
@history_worker
@history_access
def clear_history():
if HISTORY_BACKEND == "postgres":
history_db_call("clear_sms")
return {"status": "success"}
if os.path.exists(SMS_HISTORY_FILE):
os.remove(SMS_HISTORY_FILE)
try:
ws = get_sms_history_worksheet()
ws.batch_clear(["A2:Z10000"])
except Exception as e:
print(f"구글 시트 문자내역 전체 삭제 실패: {e}")
return {"status": "success"}
@app.delete("/api/sms/history/records/{record_id}")
@history_worker
@history_access
def delete_sms_history_record(record_id: int):
if HISTORY_BACKEND != "postgres":
raise HTTPException(status_code=409, detail="내역 화면을 새로고침해주세요.")
if not history_db_call("delete", "sms", record_id):
raise HTTPException(status_code=404, detail="이미 삭제된 내역입니다. 새로고침해주세요.")
return {"status": "success"}
@app.delete("/api/sms/history/{index}")
@history_worker
@history_access
def delete_history_item(index: int):
if HISTORY_BACKEND == "postgres":
raise HTTPException(status_code=409, detail="내역 화면을 새로고침한 후 다시 삭제해주세요.")
try:
ws = get_sms_history_worksheet()
rows = ws.get_all_values()
# 범위 밖 index로 엉뚱한 행을 지우지 않는다.
if index < 0 or len(rows) <= index + 1:
raise HTTPException(status_code=404, detail="이미 삭제된 내역입니다. 새로고침해주세요.")
timestamp_to_delete = rows[index + 1][0] if rows[index + 1] else None
ws.delete_rows(index + 2)
if timestamp_to_delete and os.path.exists(SMS_HISTORY_FILE):
_write_jsonl(SMS_HISTORY_FILE, [
item for item in _read_jsonl(SMS_HISTORY_FILE)
if item.get("timestamp") != timestamp_to_delete
])
except HTTPException:
raise
except Exception as e:
print(f"구글 시트 문자내역 항목 삭제 실패: {e}")
return {"status": "success"}
@app.get("/api/manual/history")
@history_worker
@history_access
def get_manual_history():
today_prefix = now_kst().strftime("%Y-%m-%d")
if HISTORY_BACKEND == "postgres":
return history_db_call("list_records", "manual", day=today_prefix)
local_history = {
item["timestamp"]: item for item in _read_jsonl(MANUAL_HISTORY_FILE)
if str(item.get("timestamp", "")).startswith(today_prefix)
}
history = []
try:
ws = get_manual_history_worksheet()
rows = ws.get_all_values()
if rows and len(rows) > 1:
for row in rows[1:]:
if not row or not row[0].strip():
continue
timestamp = row[0]
if not timestamp.startswith(today_prefix):
continue
if timestamp in local_history:
history.append(local_history[timestamp])
else:
customer_name = row[1] if len(row) > 1 else ""
total_amount_str = str(row[2]).replace(",", "") if len(row) > 2 else "0"
total_amount = int(total_amount_str) if total_amount_str.lstrip('-').isdigit() else total_amount_str
history.append({
"timestamp": timestamp,
"customer_name": customer_name,
"total_amount": total_amount
})
return history
except Exception as e:
print(f"구글 시트에서 수동발주 기록을 읽어오는 중 에러: {e}")
return list(local_history.values())
@app.post("/api/manual/history")
@history_worker
@history_access
def add_manual_history(data: dict):
if HISTORY_BACKEND == "postgres":
return {"status": "success", "id": history_db_call("add", "manual", data)}
today_prefix = now_kst().strftime("%Y-%m-%d")
# 로컬 파일에는 오늘 내역만 남긴다.
local_history = [
item for item in _read_jsonl(MANUAL_HISTORY_FILE)
if str(item.get("timestamp", "")).startswith(today_prefix)
]
local_history.append(data)
_write_jsonl(MANUAL_HISTORY_FILE, local_history)
try:
ws = get_manual_history_worksheet()
row = [
data.get("timestamp", ""),
data.get("customer_name", ""),
data.get("total_amount", 0)
]
ws.append_row(row, value_input_option='USER_ENTERED')
except Exception as e:
print(f"구글 시트 수동발주내역 기록 실패: {e}")
return {"status": "success"}
def delete_manual_order_rows(timestamp):
"""Keep cancellation of the active Google order queue, separate from history."""
ws = get_manual_worksheet()
rows = ws.get_all_values()
# Delete exact matching rows in one request, from bottom to top.
requests = [{"deleteDimension": {"range": {
"sheetId": ws.id, "dimension": "ROWS", "startIndex": index, "endIndex": index + 1,
}}} for index in reversed(range(1, len(rows))) if rows[index] and rows[index][0] == timestamp]
if requests:
ws.spreadsheet.batch_update({"requests": requests})
@app.delete("/api/manual/history/records/{record_id}")
@manual_worker
@google_history_access
def delete_manual_history_record(record_id: int):
if HISTORY_BACKEND != "postgres":
raise HTTPException(status_code=409, detail="내역 화면을 새로고침해주세요.")
if MANUAL_ORDERS_BACKEND == "postgres":
manual_db_call("delete_history", record_id)
return {"status": "success"}
record = history_db_call("get_manual", record_id)
if record is None:
raise HTTPException(status_code=404, detail="이미 삭제된 내역입니다. 새로고침해주세요.")
if history_db_call("manual_timestamp_count", record["timestamp"]) > 1:
raise HTTPException(status_code=409, detail="같은 일시의 수동발주가 여러 건입니다. 발주 시트에서 대상 주문을 먼저 확인해주세요.")
try:
delete_manual_order_rows(record["timestamp"])
except Exception as exc:
raise HTTPException(status_code=503, detail="발주 시트 삭제를 확인하지 못했습니다. 내역을 보존했습니다. 발주 시트 확인 후 다시 시도해주세요.") from exc
history_db_call("delete", "manual", record_id)
return {"status": "success"}
@app.delete("/api/manual/history/{timestamp}")
@google_worker
@history_access
def delete_manual_history(timestamp: str):
if HISTORY_BACKEND == "postgres":
raise HTTPException(status_code=409, detail="내역 화면을 새로고침한 후 다시 삭제해주세요.")
# 구글 시트에서 삭제
try:
ws = get_manual_worksheet()
rows = ws.get_all_values()
start_idx = None
end_idx = None
for i, row in enumerate(rows):
if row and row[0] == timestamp:
if start_idx is None:
start_idx = i + 1
end_idx = i + 1
if start_idx:
ws.delete_rows(start_idx, end_idx)
except Exception as e:
print(f"구글 시트 수동발주 삭제 실패: {e}")
try:
ws2 = get_manual_history_worksheet()
rows2 = ws2.get_all_values()
for i, row in enumerate(rows2):
if row and row[0] == timestamp:
ws2.delete_rows(i + 1)
break
except Exception as e:
print(f"구글 시트 수동발주내역 시트 삭제 실패: {e}")
# 로컬에서 삭제
if os.path.exists(MANUAL_HISTORY_FILE):
_write_jsonl(MANUAL_HISTORY_FILE, [
item for item in _read_jsonl(MANUAL_HISTORY_FILE) if item.get("timestamp") != timestamp
])
return {"status": "success"}
@app.get("/api/fonts")
async def get_fonts():
fonts = set()
if sys.platform == 'win32':
try:
import winreg
for hkey in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]:
try:
key = winreg.OpenKey(hkey, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
for i in range(0, winreg.QueryInfoKey(key)[1]):
name, _, _ = winreg.EnumValue(key, i)
font_name = name.split(' (')[0].strip()
if font_name:
fonts.add(font_name)
winreg.CloseKey(key)
except Exception:
pass
except Exception as e:
print(f"폰트 불러오기 오류: {e}")
if not fonts:
fonts_list = ["Inter", "Malgun Gothic", "Arial", "sans-serif"]
else:
fonts_list = sorted(list(fonts))
return fonts_list
@app.post("/api/gift/settings")
@settings_worker
@settings_update
def save_gift_settings(payload: dict):
# 하위 호환성 (기존 rules만 오는 경우)
if "rules" in payload:
rules = payload["rules"]
app_settings = payload.get("app_settings", {})
else:
rules = payload
app_settings = {}
config = read_config(force_refresh=True)
section = "SMS_GIFT_RULES"
if section not in config:
config.add_section(section)
else:
config.remove_section(section)
config.add_section(section)
for k, v in rules.items():
if v:
config.set(section, k, str(v))
if app_settings:
app_section = "APP_SETTINGS"
if app_section not in config:
config.add_section(app_section)
for k, v in app_settings.items():
if v:
config.set(app_section, k, str(v))
write_config(config)
return {"status": "success"}
@app.post("/api/app/settings")
@settings_worker
@settings_update
def save_app_settings(payload: dict):
config = read_config(force_refresh=True)
app_section = "APP_SETTINGS"
if app_section not in config:
config.add_section(app_section)
for k, v in payload.items():
if v is not None:
config.set(app_section, k, str(v))
write_config(config)
return {"status": "success"}
# ----- Code DB Data Definition -----
def init_db():
conn = psycopg2.connect(**DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
cursor = conn.cursor()
# 단품 테이블
cursor.execute('''
CREATE TABLE IF NOT EXISTS single_items (
item_code TEXT PRIMARY KEY,
sabangnet_code TEXT,
name TEXT
)
''')
# 세트 테이블
cursor.execute('''
CREATE TABLE IF NOT EXISTS set_items (
item_code TEXT PRIMARY KEY,
sabangnet_code TEXT,
name TEXT
)
''')
# 세트 구성품
cursor.execute('''
CREATE TABLE IF NOT EXISTS set_components (
set_code TEXT,
single_code TEXT,
quantity INTEGER,
PRIMARY KEY (set_code, single_code),
FOREIGN KEY(set_code) REFERENCES set_items(item_code) ON DELETE CASCADE,
FOREIGN KEY(single_code) REFERENCES single_items(item_code) ON DELETE CASCADE
)
''')
conn.commit()
conn.close()
# 반품 데이터베이스 (return_db) 초기화 시도
try:
conn_return = psycopg2.connect(**RETURN_DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
cursor_return = conn_return.cursor()
# 반품 신청 테이블
cursor_return.execute('''
CREATE TABLE IF NOT EXISTS return_requests (
id SERIAL PRIMARY KEY,
request_date VARCHAR(20),
request_type VARCHAR(50),
receiver_name VARCHAR(100),
address TEXT,
phone VARCHAR(50),
tracking_no VARCHAR(100),
mall VARCHAR(100),
remarks TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 반품 입고 테이블
cursor_return.execute('''
CREATE TABLE IF NOT EXISTS return_receivings (
id SERIAL PRIMARY KEY,
receive_date VARCHAR(20),
tracking_no VARCHAR(100),
mall VARCHAR(100),
receiver_name VARCHAR(100),
phone VARCHAR(50),
remarks TEXT,
receive_status VARCHAR(50) DEFAULT '환불 대기',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 혹시 기존에 생성된 테이블에 receive_status 컬럼이 없다면 추가
try:
cursor_return.execute('ALTER TABLE return_receivings ADD COLUMN IF NOT EXISTS receive_status VARCHAR(50) DEFAULT \'환불 대기\'')
cursor_return.execute('ALTER TABLE return_receivings ADD COLUMN IF NOT EXISTS address TEXT')
except:
pass
conn_return.commit()
conn_return.close()
except Exception as e:
print(f"[Warning] return_db 초기화 실패. 데이터베이스가 아직 생성되지 않았거나 권한 문제가 있을 수 있습니다: {e}")
def get_db_conn():
return psycopg2.connect(**DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
# Code API Models
class SingleItemAdd(BaseModel):
item_code: str
sabangnet_code: str
name: str
class SetComponentData(BaseModel):
single_code: str
quantity: int
class SetItemAdd(BaseModel):
item_code: str
components: List[SetComponentData]
sabangnet_code: str = ""
name: str = ""
@app.get("/api/codes/single")
def get_single_items():
with closing(get_db_conn()) as conn, conn.cursor() as cursor:
cursor.execute("SELECT * FROM single_items ORDER BY item_code ASC")
rows = cursor.fetchall()
return {"status": "success", "data": [dict(r) for r in rows]}
@app.post("/api/codes/single")
def add_single_item(payload: SingleItemAdd):
with closing(get_db_conn()) as conn:
try:
with conn, conn.cursor() as cursor:
cursor.execute(
"INSERT INTO single_items (item_code, sabangnet_code, name) VALUES (%s, %s, %s)",
(payload.item_code, payload.sabangnet_code, payload.name)
)
except psycopg2.IntegrityError:
raise HTTPException(status_code=400, detail="이미 존재하는 단품 코드입니다.")
invalidate_milkrun_code_cache()
return {"status": "success"}
@app.put("/api/codes/single/{item_code}")
def update_single_item(item_code: str, payload: SingleItemAdd):
with closing(get_db_conn()) as conn, conn, conn.cursor() as cursor:
cursor.execute(
"UPDATE single_items SET sabangnet_code=%s, name=%s WHERE item_code=%s",
(payload.sabangnet_code, payload.name, item_code)
)
invalidate_milkrun_code_cache()
return {"status": "success"}
@app.delete("/api/codes/single/{item_code}")
def delete_single_item(item_code: str):
with closing(get_db_conn()) as conn, conn, conn.cursor() as cursor:
cursor.execute("DELETE FROM single_items WHERE item_code=%s", (item_code,))
invalidate_milkrun_code_cache()
return {"status": "success"}
@app.get("/api/codes/set")
def get_set_items():
with closing(get_db_conn()) as conn, conn.cursor() as cursor:
cursor.execute("SELECT * FROM set_items ORDER BY item_code ASC")
sets = cursor.fetchall()
# 세트마다 따로 조회하지 않고 구성품을 한 번에 읽는다.
cursor.execute("SELECT set_code, single_code, quantity FROM set_components")
components = {}
for c in cursor.fetchall():
components.setdefault(c["set_code"], []).append(
{"single_code": c["single_code"], "quantity": c["quantity"]}
)
result = [{**dict(s), "components": components.get(s["item_code"], [])} for s in sets]
return {"status": "success", "data": result}
def _insert_set_components(cursor, set_code, components):
for comp in components:
cursor.execute(
"INSERT INTO set_components (set_code, single_code, quantity) VALUES (%s, %s, %s)",
(set_code, comp.single_code, comp.quantity)
)
@app.post("/api/codes/set")
def add_set_item(payload: SetItemAdd):
with closing(get_db_conn()) as conn:
try:
with conn, conn.cursor() as cursor:
cursor.execute(
"INSERT INTO set_items (item_code, sabangnet_code, name) VALUES (%s, %s, %s)",
(payload.item_code, payload.sabangnet_code, payload.name)
)
_insert_set_components(cursor, payload.item_code, payload.components)
except psycopg2.IntegrityError:
raise HTTPException(status_code=400, detail="중복되는 세트 코드이거나 구성품에 존재하지 않는 단품 코드가 있습니다.")
invalidate_milkrun_code_cache()
return {"status": "success"}
@app.put("/api/codes/set/{item_code}")
def update_set_item(item_code: str, payload: SetItemAdd):
with closing(get_db_conn()) as conn:
try:
with conn, conn.cursor() as cursor:
cursor.execute("UPDATE set_items SET sabangnet_code=%s, name=%s WHERE item_code=%s", (payload.sabangnet_code, payload.name, item_code))
cursor.execute("DELETE FROM set_components WHERE set_code=%s", (item_code,))
_insert_set_components(cursor, item_code, payload.components)
except psycopg2.IntegrityError:
raise HTTPException(status_code=400, detail="구성품 업데이트 중 오류 발생. 유효한 단품 코드인지 확인해주세요.")
invalidate_milkrun_code_cache()
return {"status": "success"}
@app.delete("/api/codes/set/{item_code}")
def delete_set_item(item_code: str):
with closing(get_db_conn()) as conn, conn, conn.cursor() as cursor:
cursor.execute("DELETE FROM set_items WHERE item_code=%s", (item_code,))
invalidate_milkrun_code_cache()
return {"status": "success"}
# ----- 스마트스토어 & 카페24 자동발주 공통 -----
EXCEL_COLUMNS = [
'주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량',
'주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항',
'송장번호', '쇼핑몰명', '비고', '주문번호(쇼핑몰)', '주문목록'
]
def generate_order_excel(data, numeric_date, filename, is_cafe24=False, return_bytes=False):
df = pd.DataFrame(data, columns=EXCEL_COLUMNS)
address_replacements = {
"경기 ": "경기도 ",
"강원도 ": "강원특별자치도 ",
"경남 ": "경상남도 ",
"경북 ": "경상북도 ",
"광주 ": "광주광역시 ",
"대구 ": "대구광역시 ",
"대전 ": "대전광역시 ",
"부산 ": "부산광역시 ",
"서울 ": "서울특별시 ",
"울산 ": "울산광역시 ",
"인천 ": "인천광역시 ",
"전남 ": "전라남도 ",
"전북 ": "전라북도 ",
"충남 ": "충청남도 ",
"충북 ": "충청북도 "
}
if '주소' in df.columns:
for old_val, new_val in address_replacements.items():
df['주소'] = df['주소'].str.replace(old_val, new_val, regex=False)
df = df.sort_values(by=['주소', '주문번호']).reset_index(drop=True)
df['번호'] = range(1, len(df) + 1)
output = io.BytesIO()
with pd.ExcelWriter(output, engine='openpyxl') as writer:
df.to_excel(writer, index=False, sheet_name='Sheet1')
worksheet = writer.sheets['Sheet1']
from openpyxl.utils import get_column_letter
from openpyxl.styles import Alignment, PatternFill, Font
if is_cafe24:
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
else:
header_fill = PatternFill(start_color="009900", end_color="009900", fill_type="solid")
header_font = Font(name="나눔고딕", bold=True, color="FFFFFF")
data_font = Font(name="나눔고딕")
center_alignment = Alignment(horizontal="center", vertical="center")
for row in worksheet.iter_rows(min_row=1, max_row=worksheet.max_row, min_col=1, max_col=17):
for cell in row:
if cell.row == 1:
cell.fill = header_fill
cell.font = header_font
cell.alignment = center_alignment
else:
cell.font = data_font
duplicate_groups = {}
for i, rowTuple in df.iterrows():
key = (rowTuple['수령인명'], rowTuple['주소'])
if key not in duplicate_groups:
duplicate_groups[key] = []
duplicate_groups[key].append(i + 2)
color_60_lighter = PatternFill(start_color="B4C6E7", end_color="B4C6E7", fill_type="solid")
color_40_lighter = PatternFill(start_color="FFD966", end_color="FFD966", fill_type="solid")
current_toggle = True
for key, row_indices in duplicate_groups.items():
if len(row_indices) > 1:
fill = color_60_lighter if current_toggle else color_40_lighter
for r_idx in row_indices:
for c_idx in range(1, 18):
worksheet.cell(row=r_idx, column=c_idx).fill = fill
current_toggle = not current_toggle
worksheet.freeze_panes = "H2"
worksheet.auto_filter.ref = worksheet.dimensions
for idx, col in enumerate(df.columns):
col_letter = get_column_letter(idx + 1)
max_length = 0
for cell in worksheet[col_letter]:
if cell.value is not None:
val_str = str(cell.value)
length = sum(1.8 if ord(c) > 127 else 1.1 for c in val_str)
if length > max_length:
max_length = length
adjusted_width = max_length + 2
if adjusted_width > 60:
adjusted_width = 60
worksheet.column_dimensions[col_letter].width = adjusted_width
output.seek(0)
encoded_filename = urllib.parse.quote(filename)
if return_bytes:
return output.getvalue(), encoded_filename
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
return StreamingResponse(
output,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers=headers
)
def get_all_code_to_name_from_db():
code_to_name = {}
try:
with closing(get_db_conn()) as conn, conn.cursor() as cur:
cur.execute("SELECT item_code, name FROM single_items UNION ALL SELECT item_code, name FROM set_items")
for row in cur.fetchall():
code_to_name[row[0]] = row[1]
except Exception as e:
print(f"DB 매핑 오류: {e}")
return code_to_name
# 자동발주 백그라운드 작업 상태. 내려받지 않은 결과가 메모리에 계속 남지 않도록 일정 시간 후 지운다.
TASK_TTL_SECONDS = 3600
task_store = {}
def _new_task():
now = time.time()
for saved_id, saved in list(task_store.items()):
if now - saved.get("created_at", now) > TASK_TTL_SECONDS:
task_store.pop(saved_id, None)
task_id = str(uuid.uuid4())
task_store[task_id] = {
"status": "processing",
"current": 0,
"total": 0,
"file_bytes": None,
"filename": None,
"error": None,
"created_at": now,
}
return task_id
def _order_filename(now, label):
"""'05월 01일 (목요일) 1 미라네 스마트 스토어-오전.xlsx' 형태. 15시부터는 '-3시'."""
slot = "3시" if now.hour >= 15 else "오전"
return f"{now.strftime('%m월 %d일')} ({WEEKDAYS_KR[now.weekday()]}) {label}-{slot}.xlsx"
def _cafe24_error_status(error):
text = str(error)
lowered = text.lower()
if "Authentication" in text or "authenticate" in lowered or "expired" in lowered or "인증" in text or "연동" in text:
return 401
return 500
@app.post("/api/smartstore/start_download")
async def start_smartstore_download(background_tasks: BackgroundTasks, confirm: bool = Query(False)):
task_id = _new_task()
def run_task(tid):
try:
token = get_access_token()
statuses = get_payment_done_orders(token)
if not statuses:
task_store[tid]["status"] = "error"
task_store[tid]["error"] = "새로운 결제완료(배송대기) 주문이 없습니다."
task_store[tid]["status_code"] = 404
return
# 조회 구간 경계·페이지 넘김에서 같은 주문이 두 번 올 수 있어 순서를 유지한 채 중복을 없앤다.
po_ids = list(dict.fromkeys(s.get('productOrderId') for s in statuses if s.get('productOrderId')))
task_store[tid]["total"] = len(po_ids)
all_order_details = []
chunk_size = 100
for i in range(0, len(po_ids), chunk_size):
chunk = po_ids[i:i+chunk_size]
details = get_product_order_details(token, chunk)
all_order_details.extend(details)
task_store[tid]["current"] += len(chunk)
data = []
now = now_kst()
numeric_date = int(now.strftime('%Y%m%d'))
product_cache = {}
code_to_name = get_all_code_to_name_from_db()
for idx, detail in enumerate(all_order_details):
po = detail.get('productOrder', {})
order = detail.get('order', {})
shippingAddress = po.get('shippingAddress', {})
product_id = po.get('productId')
option_code = str(po.get('optionCode', ''))
seller_code = ''
if product_id:
if product_id not in product_cache:
product_cache[product_id] = get_product_details(token, product_id)
p_data = product_cache[product_id]
seller_code = p_data.get('originProduct', {}).get('detailAttribute', {}).get('sellerCodeInfo', {}).get('sellerManagementCode', '')
if not seller_code and option_code:
option_info = p_data.get('originProduct', {}).get('detailAttribute', {}).get('optionInfo', {})
found_opt_code = ''
for opt in option_info.get('optionCombinations', []):
if str(opt.get('id', '')) == option_code:
found_opt_code = opt.get('sellerManagerCode', '')
break
if not found_opt_code:
for opt in option_info.get('optionStandards', []):
if str(opt.get('id', '')) == option_code:
found_opt_code = opt.get('sellerManagerCode', '')
break
if found_opt_code:
seller_code = found_opt_code
final_quantity = int(po.get('quantity', 1))
if seller_code and '_' in seller_code:
parts = seller_code.rsplit('_', 1)
if len(parts) == 2 and parts[1].isdigit():
seller_code = parts[0]
final_quantity = final_quantity * int(parts[1])
base_address = shippingAddress.get('baseAddress', '')
detailed_address = shippingAddress.get('detailedAddress', '')
full_address = f"{base_address} {detailed_address}".strip()
final_item_code = seller_code or po.get('optionManageCode', '') or po.get('sellerProductCode', '')
original_product_name = po.get('productName', '')
product_name = code_to_name.get(final_item_code, original_product_name)
option_info = po.get('productOption', '')
if option_info:
order_list = f"{product_name} [{option_info}]=/{po.get('quantity', 1)}"
else:
order_list = f"{product_name}=/{po.get('quantity', 1)}"
row = {
'주문날짜': numeric_date,
'번호': idx + 1,
'주문번호': po.get('productOrderId', ''),
'수령인명': shippingAddress.get('name', ''),
'상품코드': final_item_code,
'상품명': product_name,
'수량': final_quantity,
'주소': full_address,
'우편번호': '',
'수령인 전화번호': shippingAddress.get('tel1', ''),
'수령인 휴대폰': shippingAddress.get('tel1', ''),
'배송시 요구사항': po.get('shippingMemo', ''),
'송장번호': '',
'쇼핑몰명': '스마트스토어',
'비고': '',
'주문번호(쇼핑몰)': order.get('orderId', ''),
'주문목록': order_list
}
data.append(row)
filename = _order_filename(now, "1 미라네 스마트 스토어")
file_bytes, enc_name = generate_order_excel(data, numeric_date, filename, return_bytes=True)
# 파일이 만들어진 뒤에만 발주확인한다. (먼저 확인하면 파일 생성 실패 시 주문 상태만 넘어간다)
if confirm:
for i in range(0, len(po_ids), chunk_size):
confirm_orders(token, po_ids[i:i+chunk_size])
task_store[tid]["current"] = task_store[tid]["total"]
task_store[tid]["file_bytes"] = file_bytes
task_store[tid]["filename"] = enc_name
task_store[tid]["status"] = "completed"
except Exception as e:
task_store[tid]["status"] = "error"
task_store[tid]["error"] = str(e)
task_store[tid]["status_code"] = 500
background_tasks.add_task(run_task, task_id)
return {"status": "success", "task_id": task_id}
def _clean_excel_text(value):
"""엑셀에서 숫자로 읽힌 번호의 끝 '.0'만 떼어낸다. (중간의 '.0'은 건드리지 않는다)"""
text = str(value).strip()
if text.lower() == "nan":
return ""
return text[:-2] if re.fullmatch(r"\d+\.0", text) else text
def _read_invoice_rows(filename, content):
"""송장 엑셀에서 (주문번호(쇼핑몰), 송장번호) 목록을 읽는다. 사용자에게 보여줄 문제는 ValueError."""
if (filename or "").lower().endswith('.xls'):
try:
df = pd.read_excel(io.BytesIO(content), engine='xlrd')
except Exception:
try:
df = pd.read_html(io.BytesIO(content))[0]
except Exception as e2:
raise ValueError(f"xls 파일 파싱 실패: {str(e2)}")
else:
df = pd.read_excel(io.BytesIO(content), engine='openpyxl')
if '주문번호(쇼핑몰)' not in df.columns or '송장번호' not in df.columns:
raise ValueError("엑셀에 '주문번호(쇼핑몰)' 또는 '송장번호' 컬럼이 없습니다.")
df = df[df['송장번호'].notna() & (df['송장번호'] != '')]
if df.empty:
raise ValueError("송장번호가 입력된 데이터가 없습니다.")
rows = []
for order_no, tracking in zip(df['주문번호(쇼핑몰)'], df['송장번호']):
order_no = _clean_excel_text(order_no)
tracking = _clean_excel_text(tracking).split(',')[0].strip()
if order_no and tracking:
rows.append((order_no, tracking))
if not rows:
raise ValueError("유효한 송장 매핑 데이터가 없습니다.")
return rows
@app.post("/api/upload_invoices")
def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str = Form("CJGLS")):
try:
try:
rows = _read_invoice_rows(file.filename, file.file.read())
except ValueError as e:
return JSONResponse({"status": "error", "message": str(e)}, status_code=400)
dispatch_list = [{
"productOrderId": po_id,
"deliveryMethod": "DELIVERY",
"deliveryCompanyCode": deliveryCompanyCode,
"trackingNumber": tracking_num
} for po_id, tracking_num in rows]
token = get_access_token()
success_count = 0
fail_list = []
chunk_size = 100
for i in range(0, len(dispatch_list), chunk_size):
chunk = dispatch_list[i:i+chunk_size]
result = dispatch_orders(token, chunk)
results = result.get('data', {}).get('successProductOrderIds', [])
success_count += len(results)
fail_list.extend(result.get('data', {}).get('failProductOrderInfos', []))
return {
"status": "success",
"success_count": success_count,
"fail_count": len(fail_list),
"fails": fail_list,
"total_processed": len(dispatch_list)
}
except Exception as e:
return JSONResponse({"status": "error", "message": str(e)}, status_code=500)
CAFE24_OAUTH_STATE_TTL_SECONDS = 600
cafe24_oauth_states = {}
def _get_cafe24_redirect_uri(request: Request) -> str:
configured_uri = os.getenv("CAFE24_REDIRECT_URI", "").strip()
if configured_uri:
return configured_uri
return f"{str(request.base_url).rstrip('/')}/admin/oauth/callback"
@app.get("/api/cafe24/status")
async def cafe24_status():
return cafe24_api.get_token_status()
@app.get("/api/cafe24/login")
async def cafe24_login(request: Request):
now = time.time()
for saved_state, saved_data in list(cafe24_oauth_states.items()):
if now - saved_data["created_at"] > CAFE24_OAUTH_STATE_TTL_SECONDS:
cafe24_oauth_states.pop(saved_state, None)
state = secrets.token_urlsafe(32)
redirect_uri = _get_cafe24_redirect_uri(request)
cafe24_oauth_states[state] = {"redirect_uri": redirect_uri, "created_at": now}
url = cafe24_api.get_auth_url(redirect_uri=redirect_uri, state=state)
return RedirectResponse(url)
def _script_string(value):
"""<script> 안에 넣을 JS 문자열. '</script>'로 태그를 닫고 빠져나가지 못하게 한다."""
return json.dumps(value, ensure_ascii=False).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
def _alert_and_return(message, status_code=200):
# '/'로 보내면 서브경로(/corm) 밖의 ERP 첫 화면으로 가 버린다.
return HTMLResponse(
f"<script>alert({_script_string(message)}); window.location.href={_script_string(APP_ROOT_PATH + '/')};</script>",
status_code=status_code,
)
@app.get("/api/cafe24/callback")
@app.get("/admin/oauth/callback")
async def cafe24_callback(code: str = "", state: str = "", error: str = ""):
if error:
return _alert_and_return(f"카페24 인증이 취소되었거나 실패했습니다: {error}", 400)
saved = cafe24_oauth_states.pop(state, None) if state else None
if not saved or time.time() - saved["created_at"] > CAFE24_OAUTH_STATE_TTL_SECONDS:
return _alert_and_return("인증 요청이 만료되었거나 올바르지 않습니다. 다시 연동해주세요.", 400)
try:
await run_in_threadpool(cafe24_api.request_new_token, code, redirect_uri=saved["redirect_uri"])
return _alert_and_return("카페24 연동 성공!")
except Exception as e:
return _alert_and_return(f"인증 실패: {e}", 400)
@app.post("/api/cafe24/start_download")
async def start_cafe24_download(background_tasks: BackgroundTasks):
task_id = _new_task()
def run_task(tid):
try:
total_count = cafe24_api.get_cafe24_orders_count(status="N20")
task_store[tid]["total"] = total_count
def progress_callback(current):
task_store[tid]["current"] = current
orders = cafe24_api.get_cafe24_orders(status="N20", progress_callback=progress_callback)
if not orders:
task_store[tid]["status"] = "error"
task_store[tid]["error"] = "새로운 배송준비중 주문이 없습니다."
task_store[tid]["status_code"] = 404
return
data = []
now = now_kst()
numeric_date = int(now.strftime('%Y%m%d'))
code_to_name = get_all_code_to_name_from_db()
exchange_customers = []
for idx, order in enumerate(orders):
items = order.get('items', [])
receivers = order.get('receivers', [])
receiver = receivers[0] if receivers else {}
has_exchange = False
for item in items:
if item.get('exchange_request_date') or item.get('exchange_date') or str(item.get('status_code', '')).startswith('E'):
has_exchange = True
break
if has_exchange:
exchange_customers.append({
"name": receiver.get('name', ''),
"phone": receiver.get('cellphone') or receiver.get('phone', ''),
"order_no": order.get('order_id', '')
})
continue
address_full = receiver.get('address_full', '')
if not address_full:
address_full = f"{receiver.get('address1', '')} {receiver.get('address2', '')}".strip()
full_address = address_full
for item in items:
if not str(item.get('status_code') or '').startswith('N'):
continue
seller_code = item.get('custom_variant_code') or item.get('item_code') or item.get('custom_product_code') or item.get('product_code', '')
final_quantity = int(item.get('quantity', 1))
if seller_code and '_' in seller_code:
parts = seller_code.rsplit('_', 1)
if len(parts) == 2 and parts[1].isdigit():
seller_code = parts[0]
final_quantity = final_quantity * int(parts[1])
original_product_name = item.get('product_name', '')
product_name = code_to_name.get(seller_code, original_product_name)
original_quantity = item.get('quantity', 1)
option_info = item.get('option_value', '')
if option_info:
order_list = f"{original_product_name}/{option_info}/{original_quantity}"
else:
order_list = f"{original_product_name}/{original_quantity}"
row = {
'주문날짜': numeric_date,
'번호': 0,
'주문번호': item.get('order_item_code') or order.get('order_id', ''),
'수령인명': receiver.get('name', ''),
'상품코드': seller_code,
'상품명': product_name,
'수량': final_quantity,
'주소': full_address,
'우편번호': receiver.get('zipcode', ''),
'수령인 전화번호': receiver.get('phone', ''),
'수령인 휴대폰': receiver.get('cellphone', ''),
'배송시 요구사항': receiver.get('shipping_message', ''),
'송장번호': '',
'쇼핑몰명': '자사몰',
'비고': order.get('admin_additional_amount_name', ''),
'주문번호(쇼핑몰)': order.get('order_id', ''),
'주문목록': order_list
}
data.append(row)
filename = _order_filename(now, "0 미라네 자사몰 발주")
file_bytes, enc_name = generate_order_excel(data, numeric_date, filename, is_cafe24=True, return_bytes=True)
task_store[tid]["current"] = task_store[tid]["total"]
task_store[tid]["file_bytes"] = file_bytes
task_store[tid]["filename"] = enc_name
task_store[tid]["exchange_customers"] = exchange_customers
task_store[tid]["status"] = "completed"
except Exception as e:
task_store[tid]["status"] = "error"
task_store[tid]["error"] = str(e)
task_store[tid]["status_code"] = _cafe24_error_status(e)
background_tasks.add_task(run_task, task_id)
return {"status": "success", "task_id": task_id}
@app.get("/api/tasks/progress/{task_id}")
async def get_task_progress(task_id: str):
if task_id not in task_store:
return JSONResponse({"status": "error", "message": "작업을 찾을 수 없습니다."}, status_code=404)
task_data = task_store[task_id]
if task_data["status"] == "error":
status_code = task_data.get("status_code", 500)
return JSONResponse({"status": "error", "message": task_data["error"]}, status_code=status_code)
return {
"status": task_data["status"],
"current": task_data["current"],
"total": task_data["total"]
}
@app.get("/api/tasks/download_file/{task_id}")
async def download_task_file(task_id: str):
if task_id not in task_store or task_store[task_id]["status"] != "completed":
return JSONResponse({"status": "error", "message": "파일이 아직 준비되지 않았거나 만료되었습니다."}, status_code=404)
task_data = task_store[task_id]
output = io.BytesIO(task_data["file_bytes"])
enc_name = task_data["filename"]
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{enc_name}"
}
# 메모리 정리 (1회 다운로드 후 삭제)
del task_store[task_id]
return StreamingResponse(
output,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers=headers
)
@app.post("/api/cafe24/upload_invoices")
def cafe24_upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str = Form("0004")):
try:
try:
rows = _read_invoice_rows(file.filename, file.file.read())
except ValueError as e:
return JSONResponse({"status": "error", "message": str(e)}, status_code=400)
dispatch_list = [{
"order_id": po_id,
"tracking_no": tracking_num,
"shipping_company_code": deliveryCompanyCode
} for po_id, tracking_num in rows]
results = cafe24_api.update_cafe24_tracking(dispatch_list)
return {
"status": "success",
"success_count": len(results["success"]),
"fail_count": len(results["fail"]),
"fails": results["fail"],
"total_processed": len(dispatch_list)
}
except Exception as e:
return JSONResponse({"status": "error", "message": str(e)}, status_code=_cafe24_error_status(e))
# ==========================================
# 반품 관리 API
# ==========================================
if __name__ == "__main__":
import uvicorn
host = os.getenv("HOST", "0.0.0.0")
port = int(os.getenv("PORT", "8002"))
uvicorn.run(app, host=host, port=port)