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>
This commit is contained in:
2026-10-22 20:30:26 +09:00
parent ae50500655
commit 7046a504a1
9 changed files with 561 additions and 667 deletions
+271 -382
View File
@@ -2,12 +2,10 @@ import os
import sys
import psycopg2
import psycopg2.extras
import os
import time
import json
import re
import io
import math
import datetime
import functools
import urllib.request
@@ -15,10 +13,11 @@ 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, Body, UploadFile, File, Form, Query, BackgroundTasks
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, FileResponse, RedirectResponse
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
@@ -31,7 +30,7 @@ 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, Any
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,
@@ -89,15 +88,7 @@ RETURN_DB_CONFIG = {
'user': _PG_USER,
'password': _PG_PASSWORD,
}
# 3. 주문정보 조회용 DB
ORDER_DB_CONFIG = {
'host': _PG_HOST,
'port': _PG_PORT,
'dbname': os.getenv('ORDERLIST_DB', 'orderlist_db'),
'user': _PG_USER,
'password': _PG_PASSWORD,
}
# 주문정보 조회용 DB(orderlist_db)는 routers/returns.py 에서 사용한다.
# ==========================================
# Google Sheets
@@ -116,7 +107,7 @@ app.add_middleware(AuthGuardMiddleware)
@app.get("/health/db")
async def health_db():
def health_db():
"""DB ping — 인증 불필요. dbx-main 의 헬스 배지가 이 경로를 폴링한다."""
try:
conn = psycopg2.connect(**DB_CONFIG, connect_timeout=3)
@@ -178,6 +169,15 @@ _settings_cache = SettingsCache(
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:
@@ -500,11 +500,9 @@ class OrderPayload(BaseModel):
total_amount: int = 0
def get_current_time_info():
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
now = datetime.datetime.now(korea_tz)
now = now_kst()
time_str = "오후" if now.hour >= 12 else "오전"
day_names_kr = ["월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"]
day_name = day_names_kr[now.weekday()]
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
@@ -660,10 +658,7 @@ def submit_order_submit(payload: OrderPayload):
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)
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}")
@@ -762,10 +757,9 @@ def get_manual_export(export_id: uuid.UUID):
@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":
now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
weekdays = ["월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"]
filename = f"{now:%m}월 {now:%d}일 ({weekdays[now.weekday()]}) 5 수동발주.xlsx"
content, export_id = manual_db_call("export_and_archive", filename)
return manual_file_response(content, filename, export_id)
try:
@@ -778,20 +772,12 @@ def download_and_clear_sheet():
access_token = creds.token
worksheet = get_manual_worksheet()
sheet_gid = worksheet.id
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()
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
now = datetime.datetime.now(korea_tz)
weekdays = ["월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"]
weekday_str = weekdays[now.weekday()]
date_str = f"{now.strftime('%m')}월 {now.strftime('%d')}일 ({weekday_str})"
filename = f"{date_str} 5 수동발주.xlsx"
# Clear sheet values instantly
worksheet.batch_clear(["A2:Z10000"])
@@ -811,15 +797,7 @@ def download_and_clear_sheet():
}
worksheet.spreadsheet.batch_update(body)
encoded_filename = urllib.parse.quote(filename)
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
return StreamingResponse(
io.BytesIO(content),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers=headers
)
return manual_file_response(content, filename)
except Exception as e:
err_str = str(e)
if not err_str or err_str.strip() == "{}":
@@ -828,13 +806,36 @@ def download_and_clear_sheet():
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_history = {}
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
@@ -845,17 +846,6 @@ def get_history():
merged[key] = sheet_item[key]
return merged
if os.path.exists(SMS_HISTORY_FILE):
with open(SMS_HISTORY_FILE, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
item = json.loads(line)
if "timestamp" in item:
local_history[item["timestamp"]] = item
except:
pass
history = []
try:
ws = get_sms_history_worksheet()
@@ -893,9 +883,7 @@ def get_history():
except Exception as e:
print(f"구글 시트에서 기록을 읽어오는 중 에러: {e}")
if os.path.exists(SMS_HISTORY_FILE):
return [json.loads(line) for line in open(SMS_HISTORY_FILE, 'r', encoding='utf-8') if line.strip()]
return []
return local_entries
@app.post("/api/sms/history")
@history_worker
@@ -978,56 +966,38 @@ def delete_history_item(index: int):
try:
ws = get_sms_history_worksheet()
rows = ws.get_all_values()
timestamp_to_delete = None
if len(rows) > index + 1:
timestamp_to_delete = rows[index + 1][0] if len(rows[index+1]) > 0 else None
# 범위 밖 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):
local_history = []
with open(SMS_HISTORY_FILE, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
local_history.append(json.loads(line))
except:
pass
local_history = [item for item in local_history if item.get("timestamp") != timestamp_to_delete]
with open(SMS_HISTORY_FILE, 'w', encoding='utf-8') as f:
for entry in local_history:
json.dump(entry, f, ensure_ascii=False)
f.write('\n')
_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"}
import sys
@app.get("/api/manual/history")
@history_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")
today_prefix = now_kst().strftime("%Y-%m-%d")
if HISTORY_BACKEND == "postgres":
return history_db_call("list_records", "manual", day=today_prefix)
local_history = {}
if os.path.exists(MANUAL_HISTORY_FILE):
with open(MANUAL_HISTORY_FILE, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
item = json.loads(line)
if item.get("timestamp", "").startswith(today_prefix):
local_history[item["timestamp"]] = item
except:
pass
local_history = {
item["timestamp"]: item for item in _read_jsonl(MANUAL_HISTORY_FILE)
if str(item.get("timestamp", "")).startswith(today_prefix)
}
history = []
try:
@@ -1064,27 +1034,14 @@ def get_manual_history():
def add_manual_history(data: dict):
if HISTORY_BACKEND == "postgres":
return {"status": "success", "id": history_db_call("add", "manual", data)}
local_history = []
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
if os.path.exists(MANUAL_HISTORY_FILE):
with open(MANUAL_HISTORY_FILE, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
item = json.loads(line)
if item.get("timestamp", "").startswith(today_prefix):
local_history.append(item)
except:
pass
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)
with open(MANUAL_HISTORY_FILE, 'w', encoding='utf-8') as f:
for entry in local_history:
json.dump(entry, f, ensure_ascii=False)
f.write('\n')
_write_jsonl(MANUAL_HISTORY_FILE, local_history)
try:
ws = get_manual_history_worksheet()
@@ -1167,19 +1124,9 @@ def delete_manual_history(timestamp: str):
# 로컬에서 삭제
if os.path.exists(MANUAL_HISTORY_FILE):
local_history = []
with open(MANUAL_HISTORY_FILE, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
local_history.append(json.loads(line))
except:
pass
local_history = [item for item in local_history if item.get("timestamp") != timestamp]
with open(MANUAL_HISTORY_FILE, 'w', encoding='utf-8') as f:
for entry in local_history:
json.dump(entry, f, ensure_ascii=False)
f.write('\n')
_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")
@@ -1260,9 +1207,7 @@ def save_app_settings(payload: dict):
write_config(config)
return {"status": "success"}
# ----- Code DB (SQLite) Data Definition -----
DB_PATH = "codes.db"
# ----- Code DB Data Definition -----
def init_db():
conn = psycopg2.connect(**DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
cursor = conn.cursor()
@@ -1344,16 +1289,7 @@ def init_db():
print(f"[Warning] return_db 초기화 실패. 데이터베이스가 아직 생성되지 않았거나 권한 문제가 있을 수 있습니다: {e}")
def get_db_conn():
conn = psycopg2.connect(**DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
return conn
def get_return_db_conn():
conn = psycopg2.connect(**RETURN_DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
return conn
def get_order_db_conn():
conn = psycopg2.connect(**ORDER_DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
return conn
return psycopg2.connect(**DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
# Code API Models
class SingleItemAdd(BaseModel):
@@ -1372,126 +1308,99 @@ class SetItemAdd(BaseModel):
name: str = ""
@app.get("/api/codes/single")
async def get_single_items():
conn = get_db_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM single_items ORDER BY item_code ASC")
rows = cursor.fetchall()
conn.close()
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")
async def add_single_item(payload: SingleItemAdd):
conn = get_db_conn()
cursor = conn.cursor()
try:
cursor.execute(
"INSERT INTO single_items (item_code, sabangnet_code, name) VALUES (%s, %s, %s)",
(payload.item_code, payload.sabangnet_code, payload.name)
)
conn.commit()
invalidate_milkrun_code_cache()
return {"status": "success"}
except psycopg2.IntegrityError:
conn.close()
raise HTTPException(status_code=400, detail="이미 존재하는 단품 코드입니다.")
finally:
if conn:
conn.close()
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}")
async def update_single_item(item_code: str, payload: SingleItemAdd):
conn = get_db_conn()
cursor = conn.cursor()
cursor.execute(
"UPDATE single_items SET sabangnet_code=%s, name=%s WHERE item_code=%s",
(payload.sabangnet_code, payload.name, item_code)
)
conn.commit()
conn.close()
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}")
async def delete_single_item(item_code: str):
conn = get_db_conn()
cursor = conn.cursor()
cursor.execute("DELETE FROM single_items WHERE item_code=%s", (item_code,))
conn.commit()
conn.close()
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")
async def get_set_items():
conn = get_db_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM set_items ORDER BY item_code ASC")
sets = cursor.fetchall()
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 = []
for s in sets:
s_dict = dict(s)
cursor.execute("SELECT single_code, quantity FROM set_components WHERE set_code=%s", (s_dict["item_code"],))
comps = cursor.fetchall()
s_dict["components"] = [dict(c) for c in comps]
result.append(s_dict)
conn.close()
result = [{**dict(s), "components": components.get(s["item_code"], [])} for s in sets]
return {"status": "success", "data": result}
@app.post("/api/codes/set")
async def add_set_item(payload: SetItemAdd):
conn = get_db_conn()
cursor = conn.cursor()
try:
def _insert_set_components(cursor, set_code, components):
for comp in components:
cursor.execute(
"INSERT INTO set_items (item_code, sabangnet_code, name) VALUES (%s, %s, %s)",
(payload.item_code, payload.sabangnet_code, payload.name)
"INSERT INTO set_components (set_code, single_code, quantity) VALUES (%s, %s, %s)",
(set_code, comp.single_code, comp.quantity)
)
for comp in payload.components:
cursor.execute(
"INSERT INTO set_components (set_code, single_code, quantity) VALUES (%s, %s, %s)",
(payload.item_code, comp.single_code, comp.quantity)
)
conn.commit()
invalidate_milkrun_code_cache()
return {"status": "success"}
except psycopg2.IntegrityError:
conn.rollback()
raise HTTPException(status_code=400, detail="중복되는 세트 코드이거나 구성품에 존재하지 않는 단품 코드가 있습니다.")
finally:
if conn: conn.close()
@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}")
async def update_set_item(item_code: str, payload: SetItemAdd):
conn = get_db_conn()
cursor = conn.cursor()
try:
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,))
for comp in payload.components:
cursor.execute(
"INSERT INTO set_components (set_code, single_code, quantity) VALUES (%s, %s, %s)",
(item_code, comp.single_code, comp.quantity)
)
conn.commit()
invalidate_milkrun_code_cache()
return {"status": "success"}
except psycopg2.IntegrityError:
conn.rollback()
raise HTTPException(status_code=400, detail="구성품 업데이트 중 오류 발생. 유효한 단품 코드인지 확인해주세요.")
finally:
if conn: conn.close()
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}")
async def delete_set_item(item_code: str):
conn = get_db_conn()
cursor = conn.cursor()
cursor.execute("DELETE FROM set_items WHERE item_code=%s", (item_code,))
conn.commit()
conn.close()
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"}
@@ -1610,26 +1519,27 @@ def generate_order_excel(data, numeric_date, filename, is_cafe24=False, return_b
)
def get_all_code_to_name_from_db():
import psycopg2
import psycopg2.extras
import os
code_to_name = {}
try:
conn = psycopg2.connect(**DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
cur = conn.cursor()
cur.execute("SELECT item_code, name FROM single_items")
for row in cur.fetchall():
code_to_name[row[0]] = row[1]
cur.execute("SELECT item_code, name FROM set_items")
for row in cur.fetchall():
code_to_name[row[0]] = row[1]
conn.close()
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
@app.post("/api/smartstore/start_download")
async def start_smartstore_download(background_tasks: BackgroundTasks, confirm: bool = Query(False)):
# 자동발주 백그라운드 작업 상태. 내려받지 않은 결과가 메모리에 계속 남지 않도록 일정 시간 후 지운다.
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",
@@ -1637,8 +1547,29 @@ async def start_smartstore_download(background_tasks: BackgroundTasks, confirm:
"total": 0,
"file_bytes": None,
"filename": None,
"error": 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:
@@ -1651,7 +1582,8 @@ async def start_smartstore_download(background_tasks: BackgroundTasks, confirm:
task_store[tid]["status_code"] = 404
return
po_ids = [s.get('productOrderId') for s in statuses if s.get('productOrderId')]
# 조회 구간 경계·페이지 넘김에서 같은 주문이 두 번 올 수 있어 순서를 유지한 채 중복을 없앤다.
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 = []
@@ -1662,13 +1594,8 @@ async def start_smartstore_download(background_tasks: BackgroundTasks, confirm:
all_order_details.extend(details)
task_store[tid]["current"] += len(chunk)
if confirm:
for i in range(0, len(po_ids), chunk_size):
chunk = po_ids[i:i+chunk_size]
confirm_orders(token, chunk)
data = []
now = datetime.datetime.now()
now = now_kst()
numeric_date = int(now.strftime('%Y%m%d'))
product_cache = {}
@@ -1747,15 +1674,14 @@ async def start_smartstore_download(background_tasks: BackgroundTasks, confirm:
}
data.append(row)
weekdays = ['월요일', '화요일', '수요일', '목요일', '금요일', '토요일', '일요일']
weekday_str = weekdays[now.weekday()]
if now.hour >= 15:
filename = f"{now.strftime('%m월 %d일')} ({weekday_str}) 1 미라네 스마트 스토어-3시.xlsx"
else:
filename = f"{now.strftime('%m월 %d일')} ({weekday_str}) 1 미라네 스마트 스토어-오전.xlsx"
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
@@ -1770,48 +1696,59 @@ async def start_smartstore_download(background_tasks: BackgroundTasks, confirm:
return {"status": "success", "task_id": task_id}
@app.post("/api/upload_invoices")
async def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str = Form("CJGLS")):
try:
content = await file.read()
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
if file.filename.endswith('.xls'):
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_excel(io.BytesIO(content), engine='xlrd')
except Exception:
try:
df = pd.read_html(io.BytesIO(content))[0]
except Exception as e2:
return JSONResponse({"status": "error", "message": f"xls 파일 파싱 실패: {str(e2)}"}, status_code=400)
else:
df = pd.read_excel(io.BytesIO(content), engine='openpyxl')
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:
return JSONResponse({"status": "error", "message": "엑셀에 '주문번호(쇼핑몰)' 또는 '송장번호' 컬럼이 없습니다."}, status_code=400)
if '주문번호(쇼핑몰)' not in df.columns or '송장번호' not in df.columns:
raise ValueError("엑셀에 '주문번호(쇼핑몰)' 또는 '송장번호' 컬럼이 없습니다.")
df = df[df['송장번호'].notna() & (df['송장번호'] != '')]
df = df[df['송장번호'].notna() & (df['송장번호'] != '')]
if df.empty:
raise ValueError("송장번호가 입력된 데이터가 없습니다.")
if df.empty:
return JSONResponse({"status": "error", "message": "송장번호가 입력된 데이터가 없습니다."}, status_code=400)
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
dispatch_list = []
for index, row in df.iterrows():
po_id = str(row['주문번호(쇼핑몰)']).replace('.0', '').strip()
tracking_num = str(row['송장번호']).replace('.0', '').strip()
if ',' in tracking_num:
tracking_num = tracking_num.split(',')[0].strip()
@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)
if po_id and tracking_num and tracking_num != 'nan':
dispatch_list.append({
"productOrderId": po_id,
"deliveryMethod": "DELIVERY",
"deliveryCompanyCode": deliveryCompanyCode,
"trackingNumber": tracking_num
})
if not dispatch_list:
return JSONResponse({"status": "error", "message": "유효한 송장 매핑 데이터가 없습니다."}, 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
@@ -1824,13 +1761,10 @@ async def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str
results = result.get('data', {}).get('successProductOrderIds', [])
success_count += len(results)
fails = result.get('data', {}).get('failProductOrderInfos', [])
for f in fails:
fail_list.append(f)
fail_list.extend(result.get('data', {}).get('failProductOrderInfos', []))
return {
"status": "success",
"status": "success",
"success_count": success_count,
"fail_count": len(fail_list),
"fails": fail_list,
@@ -1840,8 +1774,6 @@ async def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str
except Exception as e:
return JSONResponse({"status": "error", "message": str(e)}, status_code=500)
from fastapi.responses import RedirectResponse
CAFE24_OAUTH_STATE_TTL_SECONDS = 600
cafe24_oauth_states = {}
@@ -1868,38 +1800,38 @@ async def cafe24_login(request: Request):
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:
message = json.dumps(f"카페24 인증이 취소되었거나 실패했습니다: {error}", ensure_ascii=False)
return HTMLResponse(f"<script>alert({message}); window.location.href='/';</script>", status_code=400)
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:
message = json.dumps("인증 요청이 만료되었거나 올바르지 않습니다. 다시 연동해주세요.", ensure_ascii=False)
return HTMLResponse(f"<script>alert({message}); window.location.href='/';</script>", status_code=400)
return _alert_and_return("인증 요청이 만료되었거나 올바르지 않습니다. 다시 연동해주세요.", 400)
try:
cafe24_api.request_new_token(code, redirect_uri=saved["redirect_uri"])
return HTMLResponse("<script>alert('카페24 연동 성공!'); window.location.href='/';</script>")
await run_in_threadpool(cafe24_api.request_new_token, code, redirect_uri=saved["redirect_uri"])
return _alert_and_return("카페24 연동 성공!")
except Exception as e:
message = json.dumps(f"인증 실패: {e}", ensure_ascii=False)
return HTMLResponse(f"<script>alert({message}); window.location.href='/';</script>", status_code=400)
task_store = {}
return _alert_and_return(f"인증 실패: {e}", 400)
@app.post("/api/cafe24/start_download")
async def start_cafe24_download(background_tasks: BackgroundTasks):
task_id = str(uuid.uuid4())
task_store[task_id] = {
"status": "processing",
"current": 0,
"total": 0,
"file_bytes": None,
"filename": None,
"error": None
}
task_id = _new_task()
def run_task(tid):
try:
@@ -1913,10 +1845,11 @@ async def start_cafe24_download(background_tasks: BackgroundTasks):
if not orders:
task_store[tid]["status"] = "error"
task_store[tid]["error"] = "새로운 배송준비중 주문이 없습니다."
task_store[tid]["status_code"] = 404
return
data = []
now = datetime.datetime.now()
now = now_kst()
numeric_date = int(now.strftime('%Y%m%d'))
code_to_name = get_all_code_to_name_from_db()
exchange_customers = []
@@ -1946,7 +1879,7 @@ async def start_cafe24_download(background_tasks: BackgroundTasks):
full_address = address_full
for item in items:
if not item.get('status_code', '').startswith('N'):
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', '')
@@ -1989,14 +1922,7 @@ async def start_cafe24_download(background_tasks: BackgroundTasks):
}
data.append(row)
weekdays = ['월요일', '화요일', '수요일', '목요일', '금요일', '토요일', '일요일']
weekday_str = weekdays[now.weekday()]
if now.hour >= 15:
filename = f"{now.strftime('%m월 %d일')} ({weekday_str}) 0 미라네 자사몰 발주-3시.xlsx"
else:
filename = f"{now.strftime('%m월 %d일')} ({weekday_str}) 0 미라네 자사몰 발주-오전.xlsx"
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"]
@@ -2006,18 +1932,9 @@ async def start_cafe24_download(background_tasks: BackgroundTasks):
task_store[tid]["status"] = "completed"
except Exception as e:
status_code = 500
if (
"Authentication" in str(e)
or "authenticate" in str(e).lower()
or "expired" in str(e).lower()
or "인증" in str(e)
or "연동" in str(e)
):
status_code = 401
task_store[tid]["status"] = "error"
task_store[tid]["error"] = str(e)
task_store[tid]["status_code"] = status_code
task_store[tid]["status_code"] = _cafe24_error_status(e)
background_tasks.add_task(run_task, task_id)
return {"status": "success", "task_id": task_id}
@@ -2062,37 +1979,18 @@ async def download_task_file(task_id: str):
@app.post("/api/cafe24/upload_invoices")
async def cafe24_upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str = Form("0004")):
def cafe24_upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str = Form("0004")):
try:
content = await file.read()
if file.filename.endswith('.xls'):
try:
df = pd.read_excel(io.BytesIO(content), engine='xlrd')
except:
df = pd.read_html(io.BytesIO(content))[0]
else:
df = pd.read_excel(io.BytesIO(content), engine='openpyxl')
try:
rows = _read_invoice_rows(file.filename, file.file.read())
except ValueError as e:
return JSONResponse({"status": "error", "message": str(e)}, status_code=400)
if '주문번호(쇼핑몰)' not in df.columns or '송장번호' not in df.columns:
return JSONResponse({"status": "error", "message": "엑셀에 '주문번호(쇼핑몰)' 또는 '송장번호' 컬럼이 없습니다."}, status_code=400)
df = df[df['송장번호'].notna() & (df['송장번호'] != '')]
if df.empty:
return JSONResponse({"status": "error", "message": "송장번호가 입력된 데이터가 없습니다."}, status_code=400)
dispatch_list = []
for index, row in df.iterrows():
po_id = str(row['주문번호(쇼핑몰)']).replace('.0', '').strip()
tracking_num = str(row['송장번호']).replace('.0', '').strip()
if ',' in tracking_num:
tracking_num = tracking_num.split(',')[0].strip()
if po_id and tracking_num and tracking_num != 'nan':
dispatch_list.append({
"order_id": po_id,
"tracking_no": tracking_num,
"shipping_company_code": deliveryCompanyCode
})
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 {
@@ -2103,16 +2001,7 @@ async def cafe24_upload_invoices(file: UploadFile = File(...), deliveryCompanyCo
"total_processed": len(dispatch_list)
}
except Exception as e:
status_code = 500
if (
"Authentication" in str(e)
or "authenticate" in str(e).lower()
or "expired" in str(e).lower()
or "인증" in str(e)
or "연동" in str(e)
):
status_code = 401
return JSONResponse({"status": "error", "message": str(e)}, status_code=status_code)
return JSONResponse({"status": "error", "message": str(e)}, status_code=_cafe24_error_status(e))
# ==========================================
# 반품 관리 API