feat: v9.1 업그레이드 — CS 기록 메뉴 + 반품 목록 검색 + 구글 연동 안정화

원본(CS 통합 프로그램 v9.1, 2026.09.03)을 서버판에 병합. 서버용 개조는 유지:
SSO(AuthGuard·SessionMiddleware), /corm 서브경로(root_path·APP_BASE_PATH),
X-Service-Token, /health/db, 환경변수 DB 설정, cafe24/naver 키 환경변수.

- CS 기록 메뉴(routers/cs_records.py, cs_records.js/css): 달력별 기록·완료·복사·
  다음 업무일 이월, 상시 메모(폴더·색), 일정, 엑셀 내려받기/업로드.
  표는 itemcode_db 에 자동 생성(CREATE TABLE IF NOT EXISTS). DB 설정은 원본의
  하드코딩 대신 CS_RECORD_DB_* → POSTGRES_*/ITEMCODE_DB 환경변수.
- New CS 누락·파손·불량·오배송 발주 → CS 기록 자동 저장.
- 반품 신청/입고 목록: 최근 3개월 기본, 전체 보기, 원송장번호 전체 검색.
- google_runtime.py: 구글 호출 시간 제한·전용 작업 슬롯, 설정 시트 스냅샷 캐시
  (예전 10분 인메모리 캐시와 /api/config/refresh 대체), 설정 저장 한 번에 원자적으로.
- 밀크런: 탭을 열 때만 구글 시트 조회.
- 자동발주 메뉴는 원본처럼 막지 않고 그대로 둠, 엑셀 내려받기 링크도 /corm 경로.
- requirements: holidays 추가. tests/test_google_resilience.py(서비스 토큰으로 SSO 통과).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 16:07:53 +09:00
parent 065e81bf97
commit d2fdec5c43
18 changed files with 5608 additions and 253 deletions
+143 -113
View File
@@ -10,11 +10,11 @@ import io
import math
import datetime
import configparser
import threading
import urllib.request
import urllib.parse
import uuid
import secrets
import threading
from urllib.parse import quote
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks
@@ -32,6 +32,10 @@ from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
from google_runtime import (
GOOGLE_READ_TIMEOUT, GoogleTimeoutSession, SettingsCache,
create_google_client, google_worker, history_access, run_google_io, settings_update,
)
# ==========================================
# SSO / 서브경로 호스팅 설정
@@ -213,6 +217,9 @@ 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)
@@ -230,6 +237,11 @@ MANUAL_SPREADSHEET_ID = os.getenv('MANUAL_SPREADSHEET_ID', '1QxFtjDurPPZd8NmtXBy
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")),
)
def env_bool(name: str, default: bool = False) -> bool:
raw = os.getenv(name)
@@ -264,38 +276,21 @@ def load_service_account_credentials(scopes):
)
# ----- Utility Functions -----
def read_config(force_refresh=False):
global _CONFIG_ROWS_CACHE, _CONFIG_ROWS_CACHE_TIME
def _load_settings_rows():
return get_settings_worksheet().get_all_values()
def read_config(force_refresh=False):
config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str
rows = []
# 1. 캐시 유효성 판단 (force_refresh 가 아니고, 캐시가 존재하며, TTL 이 지나지 않은 경우)
if not force_refresh and _CONFIG_ROWS_CACHE is not None:
if time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL:
rows = _CONFIG_ROWS_CACHE
# 2. 캐시가 없거나 만료된 경우 구글 시트에서 직접 새로 로드
if not rows:
with _CONFIG_LOCK:
# 락 대기 중 다른 스레드가 캐시를 갱신했을 수 있으므로 다시 검사 (Double-Checked Locking)
if not force_refresh and _CONFIG_ROWS_CACHE is not None and time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL:
rows = _CONFIG_ROWS_CACHE
else:
for _ in range(3):
try:
ws = get_settings_worksheet()
rows = ws.get_all_values()
break
except Exception as e:
time.sleep(1.5)
print(f"Google Sheets 불러오기 재시도 중...: {e}")
if rows:
_CONFIG_ROWS_CACHE = rows
_CONFIG_ROWS_CACHE_TIME = time.time()
try:
rows = _settings_cache.read(_load_settings_rows, force=force_refresh)
except Exception as exc:
raise HTTPException(
status_code=503,
detail="구글에서 최신 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.",
) from exc
if rows and len(rows) > 1:
for row in rows:
@@ -320,11 +315,9 @@ def read_config(force_refresh=False):
config.set(section, key, val)
else:
config.set(section, key)
config.set(section, key)
return config
def write_config(config):
global _CONFIG_ROWS_CACHE, _CONFIG_ROWS_CACHE_TIME
rows = [["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]]
for section in config.sections():
items = config.items(section)
@@ -338,23 +331,35 @@ def write_config(config):
v_parts = [p.strip() for p in v.split("|")]
rows.append([section, k] + v_parts)
for attempt in range(3):
try:
ws = get_settings_worksheet()
ws.clear()
ws.update(values=rows)
# 구글 시트에 저장이 성공하면 로컬 캐시도 즉시 최신화
with _CONFIG_LOCK:
_CONFIG_ROWS_CACHE = rows
_CONFIG_ROWS_CACHE_TIME = time.time()
return
except Exception as e:
print(f"Google Sheets 저장 시도 {attempt+1}/3 실패: {e}")
time.sleep(1.5)
print("Google Sheets에 설정을 저장하는 데 최종 실패했습니다.")
raise Exception("구글 시트 연동 오류 (할당량 초과). 잠시 후 다시 시도해주세요.")
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 -----
@@ -368,8 +373,8 @@ async def index(request: Request):
version_history = []
return templates.TemplateResponse(
request=request,
name="index.html",
request=request,
name="index.html",
context={
"version_history": version_history,
"root_path": APP_ROOT_PATH,
@@ -380,21 +385,17 @@ async def index(request: Request):
@app.get("/api/config")
async def get_config():
config = read_config()
if _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)
@app.post("/api/config/refresh")
async def refresh_config():
"""구글 시트로부터 실시간으로 설정을 동기화하여 캐시를 강제 갱신합니다."""
try:
read_config(force_refresh=True)
return {"status": "success", "message": "설정 캐시가 성공적으로 갱신되었습니다."}
except Exception as e:
raise HTTPException(status_code=500, detail=f"설정 캐시 갱신 실패: {str(e)}")
return JSONResponse(data, headers={
"X-Settings-Cache": "stale" if _settings_cache.stale else "fresh",
})
@@ -423,8 +424,10 @@ class SubgroupNamePayload(BaseModel):
name: str = ""
@app.post("/api/products/settings")
async def save_products_settings(payload: ProductsPayload):
config = read_config()
@google_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")
@@ -461,7 +464,9 @@ async def save_products_settings(payload: ProductsPayload):
return {"status": "success"}
@app.post("/api/products/subgroup-name")
async def save_product_subgroup_name(payload: SubgroupNamePayload):
@google_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()
@@ -471,7 +476,7 @@ async def save_product_subgroup_name(payload: SubgroupNamePayload):
if len(subgroup_name) > 40:
raise HTTPException(status_code=400, detail="그룹 이름은 40자 이내로 입력해주세요.")
config = read_config()
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"):
@@ -526,31 +531,20 @@ def format_phone_number(num_str):
# ----- Google Sheets Global Cache -----
# ----- Google Sheets Config Cache -----
_CONFIG_ROWS_CACHE = None
_CONFIG_ROWS_CACHE_TIME = 0.0
_CONFIG_LOCK = threading.Lock()
CONFIG_CACHE_TTL = 600.0 # 캐시 유효 시간: 10분
gs_client_global = None
worksheet_manual_global = None
worksheet_settings_global = None
worksheet_sms_history_global = None
worksheet_manual_history_global = None
# Each Google worker owns its requests session and worksheet handles.
_google_state = threading.local()
def get_gspread_client():
global gs_client_global
if gspread is None:
raise Exception("gspread 라이브러리가 없습니다.")
if gs_client_global is None:
if getattr(_google_state, "client", None) is None:
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds = load_service_account_credentials(scopes)
gs_client_global = gspread.authorize(creds)
return gs_client_global
_google_state.client = create_google_client(creds)
return _google_state.client
def get_manual_worksheet():
global worksheet_manual_global
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)
@@ -561,10 +555,11 @@ def get_manual_worksheet():
except Exception:
pass
worksheet_manual_global = ws
_google_state.manual = worksheet_manual_global
return worksheet_manual_global
def get_settings_worksheet():
global worksheet_settings_global
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)
@@ -572,10 +567,11 @@ def get_settings_worksheet():
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():
global worksheet_sms_history_global
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)
@@ -587,10 +583,11 @@ def get_sms_history_worksheet():
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():
global worksheet_manual_history_global
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)
@@ -599,6 +596,7 @@ def get_manual_history_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")
@@ -619,18 +617,12 @@ async def startup_event():
if env_bool("SKIP_GOOGLE_INIT", False):
print("SKIP_GOOGLE_INIT=1 이므로 구글 시트 선초기화를 건너뜁니다.")
else:
try:
print("구글 시트 연동 초기화 중...")
get_manual_worksheet()
get_settings_worksheet()
get_sms_history_worksheet()
get_manual_history_worksheet()
print("구글 시트 연동 완료!")
except Exception as e:
print(f"구글 시트 연동 초기화 실패 (사용 전 권한을 확인하세요): {str(e)}")
# Google unavailability must not delay startup or the DB-backed tabs.
_settings_cache.refresh_in_background(_load_settings_rows)
@app.post("/api/order/submit")
async def submit_order_submit(payload: OrderPayload):
@google_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)
@@ -665,7 +657,26 @@ async def submit_order_submit(payload: OrderPayload):
worksheet.append_rows(rows, value_input_option='USER_ENTERED')
clipboard_text = "\r\n".join(lines) + "\r\n"
return {"status": "success", "message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.", "clipboard_text": clipboard_text, "timestamp": current_datetime_str}
cs_record_saved_count = 0
cs_record_warning = ""
if order_status and lines:
try:
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
record_date = datetime.datetime.now(korea_tz).date()
event_key = f"{uuid.uuid4()}"
cs_record_saved_count = add_special_order_records(record_date, lines, event_key)
except Exception as cs_record_error:
cs_record_warning = "발주 입력은 완료됐지만 CS 기록 자동 저장에 실패했습니다."
print(f"CS 기록 자동 저장 실패: {cs_record_error}")
return {
"status": "success",
"message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.",
"clipboard_text": clipboard_text,
"timestamp": current_datetime_str,
"cs_record_saved_count": cs_record_saved_count,
"cs_record_warning": cs_record_warning,
}
except Exception as e:
err_str = str(e)
if not err_str or err_str.strip() == "{}":
@@ -673,13 +684,14 @@ async def submit_order_submit(payload: OrderPayload):
raise HTTPException(status_code=500, detail=f"수동발주 시트 접근 에러 (스프레드시트에 이메일 편집 권한을 추가했는지 확인해주세요!): {err_str}")
@app.post("/api/sheet/download_and_clear")
async def download_and_clear_sheet():
@google_worker
def download_and_clear_sheet():
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()
request = google.auth.transport.requests.Request(session=GoogleTimeoutSession())
creds.refresh(request)
access_token = creds.token
@@ -688,7 +700,7 @@ async def download_and_clear_sheet():
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) as response:
with urllib.request.urlopen(req, timeout=GOOGLE_READ_TIMEOUT) as response:
content = response.read()
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
@@ -735,7 +747,9 @@ async def download_and_clear_sheet():
@app.get("/api/sms/history")
async def get_history():
@google_worker
@history_access
def get_history():
local_history = {}
def merge_history_item(sheet_item, local_item):
if not local_item:
@@ -800,7 +814,9 @@ async def get_history():
return []
@app.post("/api/sms/history")
async def add_history(data: dict):
@google_worker
@history_access
def add_history(data: dict):
with open(SMS_HISTORY_FILE, 'a', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
f.write('\n')
@@ -839,7 +855,9 @@ async def add_history(data: dict):
return {"status": "success"}
@app.delete("/api/sms/history")
async def clear_history():
@google_worker
@history_access
def clear_history():
if os.path.exists(SMS_HISTORY_FILE):
os.remove(SMS_HISTORY_FILE)
@@ -852,7 +870,9 @@ async def clear_history():
return {"status": "success"}
@app.delete("/api/sms/history/{index}")
async def delete_history_item(index: int):
@google_worker
@history_access
def delete_history_item(index: int):
try:
ws = get_sms_history_worksheet()
rows = ws.get_all_values()
@@ -887,7 +907,9 @@ async def delete_history_item(index: int):
import sys
@app.get("/api/manual/history")
async def get_manual_history():
@google_worker
@history_access
def get_manual_history():
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
@@ -933,7 +955,9 @@ async def get_manual_history():
return list(local_history.values())
@app.post("/api/manual/history")
async def add_manual_history(data: dict):
@google_worker
@history_access
def add_manual_history(data: dict):
local_history = []
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
@@ -970,7 +994,9 @@ async def add_manual_history(data: dict):
return {"status": "success"}
@app.delete("/api/manual/history/{timestamp}")
async def delete_manual_history(timestamp: str):
@google_worker
@history_access
def delete_manual_history(timestamp: str):
# 구글 시트에서 삭제
try:
ws = get_manual_worksheet()
@@ -1041,7 +1067,9 @@ async def get_fonts():
return fonts_list
@app.post("/api/gift/settings")
async def save_gift_settings(payload: dict):
@google_worker
@settings_update
def save_gift_settings(payload: dict):
# 하위 호환성 (기존 rules만 오는 경우)
if "rules" in payload:
rules = payload["rules"]
@@ -1050,7 +1078,7 @@ async def save_gift_settings(payload: dict):
rules = payload
app_settings = {}
config = read_config()
config = read_config(force_refresh=True)
section = "SMS_GIFT_RULES"
if section not in config:
config.add_section(section)
@@ -1075,8 +1103,10 @@ async def save_gift_settings(payload: dict):
return {"status": "success"}
@app.post("/api/app/settings")
async def save_app_settings(payload: dict):
config = read_config()
@google_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)
@@ -1326,8 +1356,8 @@ async def delete_set_item(item_code: str):
# ----- 스마트스토어 & 카페24 자동발주 공통 -----
EXCEL_COLUMNS = [
'주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량',
'주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항',
'주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량',
'주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항',
'송장번호', '쇼핑몰명', '비고', '주문번호(쇼핑몰)', '주문목록'
]
@@ -1658,7 +1688,7 @@ async def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str
fail_list.append(f)
return {
"status": "success",
"status": "success",
"success_count": success_count,
"fail_count": len(fail_list),
"fails": fail_list,