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:
+14
-8
@@ -3,7 +3,7 @@ import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
# 환경변수에서 카페24 인증 정보 로드
|
||||
CLIENT_ID = os.getenv("CAFE24_CLIENT_ID", "")
|
||||
@@ -12,6 +12,12 @@ MALL_ID = os.getenv("CAFE24_MALL_ID", "miraskitchen")
|
||||
REDIRECT_URI = os.getenv("CAFE24_REDIRECT_URI", "")
|
||||
TOKEN_FILE = os.getenv("CAFE24_TOKEN_FILE", str(Path(__file__).resolve().parent / "cafe24_tokens.json"))
|
||||
REQUEST_TIMEOUT = 30
|
||||
# 카페24는 시간대 표기 없는 한국 시간을 주고받는다. 컨테이너 TZ(기본 UTC)와 무관하게 KST로 비교한다.
|
||||
KST = timezone(timedelta(hours=9))
|
||||
|
||||
|
||||
def _now_kst():
|
||||
return datetime.now(KST).replace(tzinfo=None)
|
||||
|
||||
def get_auth_url(redirect_uri=None, state=None):
|
||||
redirect_uri = redirect_uri or REDIRECT_URI
|
||||
@@ -77,7 +83,7 @@ def _save_tokens(token_data):
|
||||
if 'expires_at' not in token_data:
|
||||
# Fallback if expires_at is not provided (Cafe24 provides expires_at)
|
||||
expires_in = token_data.get('expires_in', 7200) # usually 2 hours
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in - 60) # 1 min buffer
|
||||
expires_at = _now_kst() + timedelta(seconds=expires_in - 60) # 1 min buffer
|
||||
token_data['expires_at'] = expires_at.isoformat()
|
||||
|
||||
with open(TOKEN_FILE, 'w', encoding='utf-8') as f:
|
||||
@@ -104,7 +110,7 @@ def _is_expired(value, *, leeway_seconds=0):
|
||||
expires_at = _parse_cafe24_datetime(value)
|
||||
if expires_at is None:
|
||||
return True
|
||||
now = datetime.now(expires_at.tzinfo) if expires_at.tzinfo else datetime.now()
|
||||
now = datetime.now(expires_at.tzinfo) if expires_at.tzinfo else _now_kst()
|
||||
return now >= expires_at - timedelta(seconds=leeway_seconds)
|
||||
|
||||
def get_token_status():
|
||||
@@ -163,8 +169,8 @@ def get_cafe24_orders_count(status="N20"):
|
||||
"X-Cafe24-Api-Version": "2026-03-01"
|
||||
}
|
||||
|
||||
end_date = datetime.now().strftime("%Y-%m-%d")
|
||||
start_date = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
|
||||
end_date = _now_kst().strftime("%Y-%m-%d")
|
||||
start_date = (_now_kst() - timedelta(days=7)).strftime("%Y-%m-%d")
|
||||
|
||||
url = f"https://{MALL_ID}.cafe24api.com/api/v2/admin/orders/count"
|
||||
params = {
|
||||
@@ -190,8 +196,8 @@ def get_cafe24_orders(status="N20", progress_callback=None):
|
||||
}
|
||||
|
||||
# Calculate search date range (e.g. last 7 days)
|
||||
end_date = datetime.now().strftime("%Y-%m-%d")
|
||||
start_date = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
|
||||
end_date = _now_kst().strftime("%Y-%m-%d")
|
||||
start_date = (_now_kst() - timedelta(days=7)).strftime("%Y-%m-%d")
|
||||
|
||||
url = f"https://{MALL_ID}.cafe24api.com/api/v2/admin/orders"
|
||||
|
||||
@@ -268,7 +274,7 @@ def update_cafe24_tracking(dispatch_list):
|
||||
try:
|
||||
err_data = response.json()
|
||||
reason = err_data.get('error', {}).get('message', response.text)
|
||||
except:
|
||||
except ValueError:
|
||||
reason = response.text
|
||||
|
||||
results["fail"].append({
|
||||
|
||||
@@ -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
|
||||
|
||||
+39
-27
@@ -3,9 +3,17 @@ import requests
|
||||
import time
|
||||
import bcrypt
|
||||
import base64
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
CLIENT_ID = os.getenv("NAVER_CLIENT_ID", "")
|
||||
CLIENT_SECRET = os.getenv("NAVER_CLIENT_SECRET", "")
|
||||
REQUEST_TIMEOUT = 30
|
||||
# 네이버 API는 한국 시간(+09:00)을 기대한다. 컨테이너 TZ(기본 UTC)와 무관하게 KST로 계산한다.
|
||||
KST = timezone(timedelta(hours=9))
|
||||
|
||||
|
||||
def _kst_iso(moment):
|
||||
return moment.astimezone(KST).strftime('%Y-%m-%dT%H:%M:%S.000+09:00')
|
||||
|
||||
def get_access_token():
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
@@ -28,7 +36,7 @@ def get_access_token():
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
}
|
||||
|
||||
response = requests.post(url, data=payload, headers=headers)
|
||||
response = requests.post(url, data=payload, headers=headers, timeout=REQUEST_TIMEOUT)
|
||||
if response.status_code == 200:
|
||||
return response.json().get('access_token')
|
||||
else:
|
||||
@@ -44,31 +52,35 @@ def get_payment_done_orders(token):
|
||||
|
||||
# 네이버 API는 lastChangedFrom과 lastChangedTo의 간격이 최대 24시간입니다.
|
||||
# 따라서 최근 7일의 데이터를 가져오기 위해 24시간 단위로 반복 조회합니다.
|
||||
now = time.time()
|
||||
now = datetime.now(KST)
|
||||
for days_ago in range(7, 0, -1):
|
||||
start_time = now - (days_ago * 24 * 3600)
|
||||
end_time = now - ((days_ago - 1) * 24 * 3600)
|
||||
|
||||
if days_ago == 1:
|
||||
end_time = now
|
||||
|
||||
from_date = time.strftime('%Y-%m-%dT%H:%M:%S.000+09:00', time.localtime(start_time))
|
||||
to_date = time.strftime('%Y-%m-%dT%H:%M:%S.000+09:00', time.localtime(end_time))
|
||||
|
||||
start_time = now - timedelta(days=days_ago)
|
||||
end_time = now - timedelta(days=days_ago - 1)
|
||||
|
||||
params = {
|
||||
"lastChangedFrom": from_date,
|
||||
"lastChangedTo": to_date,
|
||||
"lastChangedFrom": _kst_iso(start_time),
|
||||
"lastChangedTo": _kst_iso(end_time),
|
||||
"lastChangedType": "PAYED"
|
||||
}
|
||||
|
||||
response = requests.get(url, headers=headers, params=params)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
statuses = data.get('data', {}).get('lastChangeStatuses', [])
|
||||
all_statuses.extend(statuses)
|
||||
else:
|
||||
raise Exception(f"Failed to fetch orders ({from_date}): {response.text}")
|
||||
|
||||
|
||||
# 한 번에 최대 300건만 오므로, 'more'가 있으면 이어서 조회한다.
|
||||
while True:
|
||||
response = requests.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT)
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"Failed to fetch orders ({params['lastChangedFrom']}): {response.text}")
|
||||
data = response.json().get('data') or {}
|
||||
all_statuses.extend(data.get('lastChangeStatuses', []))
|
||||
|
||||
more = data.get('more') or {}
|
||||
if not more.get('moreFrom') or (
|
||||
more['moreFrom'] == params["lastChangedFrom"]
|
||||
and more.get('moreSequence') == params.get("moreSequence")
|
||||
):
|
||||
break
|
||||
params["lastChangedFrom"] = more['moreFrom']
|
||||
if more.get('moreSequence'):
|
||||
params["moreSequence"] = more['moreSequence']
|
||||
|
||||
return all_statuses
|
||||
|
||||
def get_product_order_details(token, product_order_ids):
|
||||
@@ -83,7 +95,7 @@ def get_product_order_details(token, product_order_ids):
|
||||
payload = {
|
||||
"productOrderIds": product_order_ids
|
||||
}
|
||||
response = requests.post(url, headers=headers, json=payload)
|
||||
response = requests.post(url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT)
|
||||
if response.status_code == 200:
|
||||
return response.json().get('data', [])
|
||||
else:
|
||||
@@ -108,7 +120,7 @@ def dispatch_orders(token, dispatch_list):
|
||||
}
|
||||
|
||||
# 발송일은 현재 시간으로 셋팅
|
||||
dispatch_date = time.strftime('%Y-%m-%dT%H:%M:%S+09:00')
|
||||
dispatch_date = datetime.now(KST).strftime('%Y-%m-%dT%H:%M:%S+09:00')
|
||||
for item in dispatch_list:
|
||||
item["dispatchDate"] = dispatch_date
|
||||
|
||||
@@ -116,7 +128,7 @@ def dispatch_orders(token, dispatch_list):
|
||||
"dispatchProductOrders": dispatch_list
|
||||
}
|
||||
|
||||
response = requests.post(url, headers=headers, json=payload)
|
||||
response = requests.post(url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
@@ -136,7 +148,7 @@ def confirm_orders(token, product_order_ids):
|
||||
"productOrderIds": product_order_ids
|
||||
}
|
||||
|
||||
response = requests.post(url, headers=headers, json=payload)
|
||||
response = requests.post(url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
@@ -148,7 +160,7 @@ def get_product_details(token, product_id):
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}"
|
||||
}
|
||||
response = requests.get(url, headers=headers)
|
||||
response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
|
||||
@@ -21,7 +21,6 @@ import urllib.request
|
||||
import pandas as pd
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
import requests
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
@@ -227,13 +226,13 @@ def _compute_milkrun_result(text: str):
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_milkrun(payload: MilkrunAnalyzeRequest):
|
||||
def analyze_milkrun(payload: MilkrunAnalyzeRequest):
|
||||
result = _compute_milkrun_result(payload.text)
|
||||
return {"status": "success", **result}
|
||||
|
||||
|
||||
@router.post("/download")
|
||||
async def download_milkrun(payload: MilkrunAnalyzeRequest):
|
||||
def download_milkrun(payload: MilkrunAnalyzeRequest):
|
||||
result = _compute_milkrun_result(payload.text)
|
||||
|
||||
df = pd.DataFrame([
|
||||
@@ -314,8 +313,7 @@ _DRIVE_CACHE_TTL_SECONDS = 300
|
||||
_drive_cache = {} # file_id -> (저장시각, 파일 bytes)
|
||||
_sheet_tabs_cache = {} # file_id -> (저장시각, 시트 목록 응답)
|
||||
|
||||
# 구글이 응답을 안 주면 무한정 매달리지 않도록 (연결 대기, 응답 대기) 초
|
||||
_HTTP_TIMEOUT = (10, 120)
|
||||
# 구글이 응답을 안 주면 무한정 매달리지 않도록 응답 대기 시간(초)을 제한한다
|
||||
_HTTP_READ_TIMEOUT = GOOGLE_READ_TIMEOUT
|
||||
|
||||
# 밀크런 출고리스트 구글 시트 (화면에서 주소를 입력하지 않아도 되도록 기본값으로 둔다)
|
||||
@@ -459,11 +457,6 @@ def _fetch_public_workbook(file_id):
|
||||
|
||||
|
||||
def _fetch_drive_workbook_authenticated(file_id):
|
||||
try:
|
||||
from google.auth.transport.requests import AuthorizedSession
|
||||
except ImportError:
|
||||
raise HTTPException(status_code=500, detail="google-auth 라이브러리가 설치되어 있지 않습니다.")
|
||||
|
||||
session = create_google_session(_load_credentials([DRIVE_SCOPE]))
|
||||
response = _drive_get(session, file_id, {"alt": "media"})
|
||||
if response.status_code != 200:
|
||||
@@ -492,8 +485,6 @@ def fetch_drive_workbook(file_id):
|
||||
def fetch_drive_file_name(file_id):
|
||||
"""파일 이름은 있으면 좋은 정보일 뿐이라, 못 가져와도 조용히 빈 값으로 둔다."""
|
||||
try:
|
||||
from google.auth.transport.requests import AuthorizedSession
|
||||
|
||||
session = create_google_session(_load_credentials([DRIVE_SCOPE]))
|
||||
response = _drive_get(session, file_id, {"fields": "name"})
|
||||
if response.status_code == 200:
|
||||
|
||||
@@ -1173,7 +1173,8 @@ def export_records():
|
||||
output = io.BytesIO()
|
||||
workbook.save(output)
|
||||
output.seek(0)
|
||||
filename = f"cs-records-{datetime.date.today().isoformat()}.xlsx"
|
||||
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).date()
|
||||
filename = f"cs-records-{today.isoformat()}.xlsx"
|
||||
return StreamingResponse(
|
||||
output,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
@@ -1219,8 +1220,8 @@ def _completed_value(value) -> bool:
|
||||
|
||||
|
||||
@router.post("/import")
|
||||
async def import_records(file: UploadFile = File(...)):
|
||||
raw = await file.read()
|
||||
def import_records(file: UploadFile = File(...)):
|
||||
raw = file.file.read()
|
||||
if len(raw) > 15 * 1024 * 1024:
|
||||
raise HTTPException(status_code=400, detail="업로드 파일은 15MB 이하여야 합니다.")
|
||||
dataframe, permanent_dataframe, schedule_dataframe = _read_import_file(file.filename or "", raw)
|
||||
|
||||
+28
-23
@@ -32,6 +32,7 @@ import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from bisect import bisect_left
|
||||
@@ -127,6 +128,8 @@ _HEADER_SCAN_ROWS = 15
|
||||
_SCAN_CACHE_MAX = 4
|
||||
_SCAN_CACHE_TTL_SECONDS = 600
|
||||
_scan_cache = OrderedDict() # sha1 -> (저장시각, 스캔결과)
|
||||
# 엔드포인트가 스레드풀에서 동시에 돌 수 있으므로 캐시 조작은 잠금 안에서 한다.
|
||||
_scan_cache_lock = threading.Lock()
|
||||
|
||||
_DATE_FORMATS = (
|
||||
"%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d",
|
||||
@@ -262,22 +265,24 @@ def _same_name(original_filename):
|
||||
# 발주서 스캔 (read_only 1회 통과 + 해시 캐시)
|
||||
# =====================================================================
|
||||
def _cache_get(key):
|
||||
entry = _scan_cache.get(key)
|
||||
if entry is None:
|
||||
return None
|
||||
saved_at, scan = entry
|
||||
if time.monotonic() - saved_at > _SCAN_CACHE_TTL_SECONDS:
|
||||
_scan_cache.pop(key, None)
|
||||
return None
|
||||
_scan_cache.move_to_end(key)
|
||||
return scan
|
||||
with _scan_cache_lock:
|
||||
entry = _scan_cache.get(key)
|
||||
if entry is None:
|
||||
return None
|
||||
saved_at, scan = entry
|
||||
if time.monotonic() - saved_at > _SCAN_CACHE_TTL_SECONDS:
|
||||
_scan_cache.pop(key, None)
|
||||
return None
|
||||
_scan_cache.move_to_end(key)
|
||||
return scan
|
||||
|
||||
|
||||
def _cache_put(key, scan):
|
||||
_scan_cache[key] = (time.monotonic(), scan)
|
||||
_scan_cache.move_to_end(key)
|
||||
while len(_scan_cache) > _SCAN_CACHE_MAX:
|
||||
_scan_cache.popitem(last=False)
|
||||
with _scan_cache_lock:
|
||||
_scan_cache[key] = (time.monotonic(), scan)
|
||||
_scan_cache.move_to_end(key)
|
||||
while len(_scan_cache) > _SCAN_CACHE_MAX:
|
||||
_scan_cache.popitem(last=False)
|
||||
|
||||
|
||||
def _collect_row(row_index, values, orders, sequence):
|
||||
@@ -593,9 +598,9 @@ def _validate_gift(gift_item_code, gift_name, gift_qty, limit):
|
||||
|
||||
|
||||
@router.post("/first-come/analyze")
|
||||
async def first_come_analyze(file: UploadFile = File(...)):
|
||||
def first_come_analyze(file: UploadFile = File(...)):
|
||||
"""업로드된 발주서에서 주문목록(Q열) 후보를 뽑아 가나다순으로 돌려준다."""
|
||||
file_bytes = await file.read()
|
||||
file_bytes = file.file.read()
|
||||
scan = scan_order_sheet(file_bytes, file.filename)
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -609,7 +614,7 @@ async def first_come_analyze(file: UploadFile = File(...)):
|
||||
|
||||
|
||||
@router.post("/first-come/preview")
|
||||
async def first_come_preview(
|
||||
def first_come_preview(
|
||||
file: UploadFile = File(...),
|
||||
selected_json: str = Form(...),
|
||||
limit: int = Form(...),
|
||||
@@ -621,7 +626,7 @@ async def first_come_preview(
|
||||
selected_names = _parse_selected(selected_json, "사은품이 지급되는 주문을 최소 1개 선택해주세요.")
|
||||
_validate_gift(gift_item_code, gift_name, gift_qty, limit)
|
||||
|
||||
file_bytes = await file.read()
|
||||
file_bytes = file.file.read()
|
||||
scan = scan_order_sheet(file_bytes, file.filename)
|
||||
result = _first_come_plan(scan, selected_names, limit)
|
||||
|
||||
@@ -647,7 +652,7 @@ async def first_come_preview(
|
||||
|
||||
|
||||
@router.post("/first-come/download")
|
||||
async def first_come_download(
|
||||
def first_come_download(
|
||||
file: UploadFile = File(...),
|
||||
selected_json: str = Form(...),
|
||||
limit: int = Form(...),
|
||||
@@ -664,7 +669,7 @@ async def first_come_download(
|
||||
selected_names = _parse_selected(selected_json, "사은품이 지급되는 주문을 최소 1개 선택해주세요.")
|
||||
gift = _validate_gift(gift_item_code, gift_name, gift_qty, limit)
|
||||
|
||||
file_bytes = await file.read()
|
||||
file_bytes = file.file.read()
|
||||
scan = scan_order_sheet(file_bytes, file.filename)
|
||||
result = _first_come_plan(scan, selected_names, limit)
|
||||
|
||||
@@ -1066,9 +1071,9 @@ def _parse_extract_mode(mode):
|
||||
|
||||
|
||||
@router.post("/event-extract/analyze")
|
||||
async def event_extract_analyze(file: UploadFile = File(...)):
|
||||
def event_extract_analyze(file: UploadFile = File(...)):
|
||||
"""업로드된 주문 CSV에서 상품명 후보를 뽑아 가나다순으로 돌려준다."""
|
||||
file_bytes = await file.read()
|
||||
file_bytes = file.file.read()
|
||||
scan = scan_event_csv(file_bytes, file.filename)
|
||||
|
||||
warnings = []
|
||||
@@ -1092,7 +1097,7 @@ async def event_extract_analyze(file: UploadFile = File(...)):
|
||||
|
||||
|
||||
@router.post("/event-extract/download")
|
||||
async def event_extract_download(
|
||||
def event_extract_download(
|
||||
file: UploadFile = File(...),
|
||||
selected_json: str = Form(...),
|
||||
mode: str = Form("product"),
|
||||
@@ -1101,7 +1106,7 @@ async def event_extract_download(
|
||||
selected_names = _parse_selected(selected_json)
|
||||
_parse_extract_mode(mode)
|
||||
|
||||
file_bytes = await file.read()
|
||||
file_bytes = file.file.read()
|
||||
scan = scan_event_csv(file_bytes, file.filename)
|
||||
result = _event_extract_select(scan, selected_names, mode)
|
||||
|
||||
|
||||
+171
-186
@@ -1,4 +1,5 @@
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from contextlib import closing
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List
|
||||
import os
|
||||
@@ -37,6 +38,20 @@ ORDER_DB_CONFIG = {
|
||||
def get_order_db_conn():
|
||||
return psycopg2.connect(**ORDER_DB_CONFIG, cursor_factory=psycopg2.extras.DictCursor)
|
||||
|
||||
|
||||
# 컨테이너 TZ(기본 UTC)와 무관하게 입고일은 한국 날짜로 기록한다.
|
||||
KST = datetime.timezone(datetime.timedelta(hours=9))
|
||||
|
||||
ORDER_LOOKUP_SQL = """
|
||||
SELECT vendor, recipient_name, recipient_phone, recipient_mobile, address
|
||||
FROM orders
|
||||
WHERE tracking_number = %s
|
||||
OR (tracking_number IS NOT NULL
|
||||
AND tracking_number != ''
|
||||
AND %s = ANY(regexp_split_to_array(tracking_number, '[,\\s/;]+')))
|
||||
ORDER BY order_date DESC LIMIT 1
|
||||
"""
|
||||
|
||||
class ReturnRequest(BaseModel):
|
||||
id: Optional[int] = None
|
||||
request_date: str
|
||||
@@ -63,23 +78,13 @@ class BulkReturnReceive(BaseModel):
|
||||
tracking_numbers: List[str]
|
||||
|
||||
@router.get("/lookup")
|
||||
async def return_lookup(tracking_no: str):
|
||||
def return_lookup(tracking_no: str):
|
||||
try:
|
||||
tracking_no = tracking_no.strip()
|
||||
conn = get_order_db_conn()
|
||||
cur = conn.cursor()
|
||||
# 주문일시(order_date 또는 upload_date) 기준 가장 최신 1건 조회
|
||||
cur.execute("""
|
||||
SELECT vendor, recipient_name, recipient_phone, recipient_mobile, address
|
||||
FROM orders
|
||||
WHERE tracking_number = %s
|
||||
OR (tracking_number IS NOT NULL
|
||||
AND tracking_number != ''
|
||||
AND %s = ANY(regexp_split_to_array(tracking_number, '[,\\s/;]+')))
|
||||
ORDER BY order_date DESC LIMIT 1
|
||||
""", (tracking_no, tracking_no))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
with closing(get_order_db_conn()) as conn, conn.cursor() as cur:
|
||||
# 주문일시(order_date) 기준 가장 최신 1건 조회
|
||||
cur.execute(ORDER_LOOKUP_SQL, (tracking_no, tracking_no))
|
||||
row = cur.fetchone()
|
||||
|
||||
if row:
|
||||
return {"success": True, "data": dict(row)}
|
||||
@@ -89,35 +94,34 @@ async def return_lookup(tracking_no: str):
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
@router.post("/request")
|
||||
async def create_return_request(req: ReturnRequest):
|
||||
def create_return_request(req: ReturnRequest):
|
||||
try:
|
||||
req.tracking_no = req.tracking_no.strip()
|
||||
conn = get_return_db_conn()
|
||||
cur = conn.cursor()
|
||||
if req.id:
|
||||
cur.execute("""
|
||||
UPDATE return_requests
|
||||
SET request_date=%s, request_type=%s, receiver_name=%s, address=%s, phone=%s, tracking_no=%s, mall=%s, remarks=%s
|
||||
WHERE id=%s
|
||||
""", (req.request_date, req.request_type, req.receiver_name, req.address, req.phone, req.tracking_no, req.mall, req.remarks, req.id))
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO return_requests
|
||||
(request_date, request_type, receiver_name, address, phone, tracking_no, mall, remarks)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (req.request_date, req.request_type, req.receiver_name, req.address, req.phone, req.tracking_no, req.mall, req.remarks))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
with closing(get_return_db_conn()) as conn, conn, conn.cursor() as cur:
|
||||
_save_return_request(cur, req)
|
||||
return {"success": True}
|
||||
except Exception as e:
|
||||
print(f"Request error: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
def _save_return_request(cur, req):
|
||||
if req.id:
|
||||
cur.execute("""
|
||||
UPDATE return_requests
|
||||
SET request_date=%s, request_type=%s, receiver_name=%s, address=%s, phone=%s, tracking_no=%s, mall=%s, remarks=%s
|
||||
WHERE id=%s
|
||||
""", (req.request_date, req.request_type, req.receiver_name, req.address, req.phone, req.tracking_no, req.mall, req.remarks, req.id))
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO return_requests
|
||||
(request_date, request_type, receiver_name, address, phone, tracking_no, mall, remarks)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (req.request_date, req.request_type, req.receiver_name, req.address, req.phone, req.tracking_no, req.mall, req.remarks))
|
||||
|
||||
@router.get("/request")
|
||||
async def get_return_requests(tracking_no: Optional[str] = None, all_records: bool = False):
|
||||
def get_return_requests(tracking_no: Optional[str] = None, all_records: bool = False):
|
||||
try:
|
||||
conn = get_return_db_conn()
|
||||
cur = conn.cursor()
|
||||
conditions, params = [], []
|
||||
if tracking_no and tracking_no.strip():
|
||||
conditions.append("regexp_replace(r.tracking_no, '[-[:space:]]', '', 'g') = %s")
|
||||
@@ -125,166 +129,153 @@ async def get_return_requests(tracking_no: Optional[str] = None, all_records: bo
|
||||
elif not all_records:
|
||||
conditions.append("r.request_date::text >= to_char(CURRENT_DATE - INTERVAL '3 months', 'YYYY-MM-DD')")
|
||||
where = ' WHERE ' + ' AND '.join(conditions) if conditions else ''
|
||||
cur.execute("""
|
||||
SELECT r.*, EXISTS (
|
||||
SELECT 1 FROM return_receivings v
|
||||
WHERE TRIM(v.tracking_no) = TRIM(r.tracking_no)
|
||||
) AS is_received
|
||||
FROM return_requests r
|
||||
""" + where + " ORDER BY r.request_date DESC, r.id DESC", params)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
with closing(get_return_db_conn()) as conn, conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT r.*, EXISTS (
|
||||
SELECT 1 FROM return_receivings v
|
||||
WHERE TRIM(v.tracking_no) = TRIM(r.tracking_no)
|
||||
) AS is_received
|
||||
FROM return_requests r
|
||||
""" + where + " ORDER BY r.request_date DESC, r.id DESC", params)
|
||||
rows = cur.fetchall()
|
||||
return {"success": True, "data": [dict(r) for r in rows]}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
@router.post("/receive/bulk")
|
||||
async def create_return_receive_bulk(req: BulkReturnReceive):
|
||||
def create_return_receive_bulk(req: BulkReturnReceive):
|
||||
try:
|
||||
from datetime import datetime
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
conn_return = get_return_db_conn()
|
||||
cur_return = conn_return.cursor()
|
||||
|
||||
conn_order = get_order_db_conn()
|
||||
cur_order = conn_order.cursor()
|
||||
|
||||
today = datetime.datetime.now(KST).strftime("%Y-%m-%d")
|
||||
success_count = 0
|
||||
duplicates = []
|
||||
seen = set()
|
||||
|
||||
for tracking_no in req.tracking_numbers:
|
||||
tracking_no = tracking_no.strip()
|
||||
if not tracking_no:
|
||||
continue
|
||||
with closing(get_return_db_conn()) as conn_return, closing(get_order_db_conn()) as conn_order:
|
||||
with conn_return, conn_return.cursor() as cur_return, conn_order.cursor() as cur_order:
|
||||
for tracking_no in req.tracking_numbers:
|
||||
tracking_no = tracking_no.strip()
|
||||
if not tracking_no:
|
||||
continue
|
||||
|
||||
mall = ""
|
||||
receiver_name = ""
|
||||
phone = ""
|
||||
address = ""
|
||||
# 단건 입고와 같이 이미 입고된 송장(또는 같은 입력 안의 중복)은 다시 넣지 않는다.
|
||||
if tracking_no in seen:
|
||||
duplicates.append(tracking_no)
|
||||
continue
|
||||
seen.add(tracking_no)
|
||||
cur_return.execute("SELECT 1 FROM return_receivings WHERE TRIM(tracking_no) = %s LIMIT 1", (tracking_no,))
|
||||
if cur_return.fetchone():
|
||||
duplicates.append(tracking_no)
|
||||
continue
|
||||
|
||||
# 1. Check return_requests
|
||||
cur_return.execute("SELECT mall, receiver_name, phone, address, request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (tracking_no,))
|
||||
req_row = cur_return.fetchone()
|
||||
if req_row:
|
||||
mall = req_row['mall'] or ""
|
||||
receiver_name = req_row['receiver_name'] or ""
|
||||
phone = req_row['phone'] or ""
|
||||
address = req_row['address'] or ""
|
||||
req_type = req_row['request_type'] or ""
|
||||
req_remarks = req_row['remarks'] or ""
|
||||
if req_remarks:
|
||||
remarks = f"{req_type}/{req_remarks}"
|
||||
else:
|
||||
remarks = req_type
|
||||
else:
|
||||
remarks = "고객이 반품"
|
||||
# 2. Check orders
|
||||
cur_order.execute("""
|
||||
SELECT vendor, recipient_name, recipient_phone, recipient_mobile, address
|
||||
FROM orders
|
||||
WHERE tracking_number = %s
|
||||
OR (tracking_number IS NOT NULL
|
||||
AND tracking_number != ''
|
||||
AND %s = ANY(regexp_split_to_array(tracking_number, '[,\\s/;]+')))
|
||||
ORDER BY order_date DESC LIMIT 1
|
||||
""", (tracking_no, tracking_no))
|
||||
ord_row = cur_order.fetchone()
|
||||
if ord_row:
|
||||
mall = ord_row['vendor'] or ""
|
||||
receiver_name = ord_row['recipient_name'] or ""
|
||||
phone = ord_row['recipient_phone'] or ord_row['recipient_mobile'] or ""
|
||||
address = ord_row['address'] or ""
|
||||
mall = ""
|
||||
receiver_name = ""
|
||||
phone = ""
|
||||
address = ""
|
||||
|
||||
# Insert into return_receivings
|
||||
cur_return.execute("""
|
||||
INSERT INTO return_receivings
|
||||
(receive_date, tracking_no, mall, receiver_name, phone, address, remarks, receive_status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (today, tracking_no, mall, receiver_name, phone, address, remarks, "환불 대기"))
|
||||
success_count += 1
|
||||
# 1. Check return_requests
|
||||
cur_return.execute("SELECT mall, receiver_name, phone, address, request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (tracking_no,))
|
||||
req_row = cur_return.fetchone()
|
||||
if req_row:
|
||||
mall = req_row['mall'] or ""
|
||||
receiver_name = req_row['receiver_name'] or ""
|
||||
phone = req_row['phone'] or ""
|
||||
address = req_row['address'] or ""
|
||||
req_type = req_row['request_type'] or ""
|
||||
req_remarks = req_row['remarks'] or ""
|
||||
remarks = f"{req_type}/{req_remarks}" if req_remarks else req_type
|
||||
else:
|
||||
remarks = "고객이 반품"
|
||||
# 2. Check orders
|
||||
cur_order.execute(ORDER_LOOKUP_SQL, (tracking_no, tracking_no))
|
||||
ord_row = cur_order.fetchone()
|
||||
if ord_row:
|
||||
mall = ord_row['vendor'] or ""
|
||||
receiver_name = ord_row['recipient_name'] or ""
|
||||
phone = ord_row['recipient_phone'] or ord_row['recipient_mobile'] or ""
|
||||
address = ord_row['address'] or ""
|
||||
|
||||
conn_return.commit()
|
||||
conn_return.close()
|
||||
conn_order.close()
|
||||
cur_return.execute("""
|
||||
INSERT INTO return_receivings
|
||||
(receive_date, tracking_no, mall, receiver_name, phone, address, remarks, receive_status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (today, tracking_no, mall, receiver_name, phone, address, remarks, "환불 대기"))
|
||||
success_count += 1
|
||||
|
||||
return {"success": True, "count": success_count}
|
||||
return {"success": True, "count": success_count, "duplicates": duplicates}
|
||||
except Exception as e:
|
||||
print(f"Bulk insert error: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/receive")
|
||||
async def create_return_receive(req: ReturnReceive):
|
||||
def create_return_receive(req: ReturnReceive):
|
||||
try:
|
||||
req.tracking_no = req.tracking_no.strip()
|
||||
conn = get_return_db_conn()
|
||||
cur = conn.cursor()
|
||||
|
||||
# 중복 송장 검사
|
||||
if req.id:
|
||||
cur.execute("""
|
||||
SELECT receive_date, receiver_name, phone, mall, receive_status, remarks
|
||||
FROM return_receivings
|
||||
WHERE TRIM(tracking_no) = %s AND id != %s
|
||||
""", (req.tracking_no, req.id))
|
||||
else:
|
||||
cur.execute("""
|
||||
SELECT receive_date, receiver_name, phone, mall, receive_status, remarks
|
||||
FROM return_receivings
|
||||
WHERE TRIM(tracking_no) = %s
|
||||
""", (req.tracking_no,))
|
||||
|
||||
dup = cur.fetchone()
|
||||
if dup:
|
||||
conn.close()
|
||||
return {
|
||||
"success": False,
|
||||
"error_type": "duplicate",
|
||||
"data": dict(dup)
|
||||
}
|
||||
|
||||
if not req.id:
|
||||
cur.execute("SELECT request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (req.tracking_no,))
|
||||
req_row = cur.fetchone()
|
||||
if not req_row:
|
||||
if req.remarks:
|
||||
if "고객이 반품" not in req.remarks:
|
||||
req.remarks = "고객이 반품 / " + req.remarks
|
||||
else:
|
||||
req.remarks = "고객이 반품"
|
||||
else:
|
||||
req_type = req_row['request_type'] or ""
|
||||
req_remarks = req_row['remarks'] or ""
|
||||
auto_remark = f"{req_type}/{req_remarks}" if req_remarks else req_type
|
||||
if not req.remarks:
|
||||
req.remarks = auto_remark
|
||||
elif auto_remark not in req.remarks:
|
||||
req.remarks = f"{auto_remark} / {req.remarks}"
|
||||
|
||||
if req.id:
|
||||
# Update existing record
|
||||
cur.execute("""
|
||||
UPDATE return_receivings
|
||||
SET receive_date=%s, tracking_no=%s, mall=%s, receiver_name=%s, phone=%s, address=%s, remarks=%s, receive_status=%s
|
||||
WHERE id=%s
|
||||
""", (req.receive_date, req.tracking_no, req.mall, req.receiver_name, req.phone, req.address, req.remarks, req.receive_status, req.id))
|
||||
else:
|
||||
# Insert new record
|
||||
cur.execute("""
|
||||
INSERT INTO return_receivings
|
||||
(receive_date, tracking_no, mall, receiver_name, phone, address, remarks, receive_status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (req.receive_date, req.tracking_no, req.mall, req.receiver_name, req.phone, req.address, req.remarks, req.receive_status))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"success": True}
|
||||
with closing(get_return_db_conn()) as conn, conn, conn.cursor() as cur:
|
||||
return _save_return_receive(cur, req)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
def _save_return_receive(cur, req):
|
||||
# 중복 송장 검사
|
||||
if req.id:
|
||||
cur.execute("""
|
||||
SELECT receive_date, receiver_name, phone, mall, receive_status, remarks
|
||||
FROM return_receivings
|
||||
WHERE TRIM(tracking_no) = %s AND id != %s
|
||||
""", (req.tracking_no, req.id))
|
||||
else:
|
||||
cur.execute("""
|
||||
SELECT receive_date, receiver_name, phone, mall, receive_status, remarks
|
||||
FROM return_receivings
|
||||
WHERE TRIM(tracking_no) = %s
|
||||
""", (req.tracking_no,))
|
||||
|
||||
dup = cur.fetchone()
|
||||
if dup:
|
||||
return {
|
||||
"success": False,
|
||||
"error_type": "duplicate",
|
||||
"data": dict(dup)
|
||||
}
|
||||
|
||||
if not req.id:
|
||||
cur.execute("SELECT request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (req.tracking_no,))
|
||||
req_row = cur.fetchone()
|
||||
if not req_row:
|
||||
if req.remarks:
|
||||
if "고객이 반품" not in req.remarks:
|
||||
req.remarks = "고객이 반품 / " + req.remarks
|
||||
else:
|
||||
req.remarks = "고객이 반품"
|
||||
else:
|
||||
req_type = req_row['request_type'] or ""
|
||||
req_remarks = req_row['remarks'] or ""
|
||||
auto_remark = f"{req_type}/{req_remarks}" if req_remarks else req_type
|
||||
if not req.remarks:
|
||||
req.remarks = auto_remark
|
||||
elif auto_remark not in req.remarks:
|
||||
req.remarks = f"{auto_remark} / {req.remarks}"
|
||||
|
||||
if req.id:
|
||||
# Update existing record
|
||||
cur.execute("""
|
||||
UPDATE return_receivings
|
||||
SET receive_date=%s, tracking_no=%s, mall=%s, receiver_name=%s, phone=%s, address=%s, remarks=%s, receive_status=%s
|
||||
WHERE id=%s
|
||||
""", (req.receive_date, req.tracking_no, req.mall, req.receiver_name, req.phone, req.address, req.remarks, req.receive_status, req.id))
|
||||
else:
|
||||
# Insert new record
|
||||
cur.execute("""
|
||||
INSERT INTO return_receivings
|
||||
(receive_date, tracking_no, mall, receiver_name, phone, address, remarks, receive_status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (req.receive_date, req.tracking_no, req.mall, req.receiver_name, req.phone, req.address, req.remarks, req.receive_status))
|
||||
return {"success": True}
|
||||
|
||||
@router.get("/receive")
|
||||
async def get_return_receives(tracking_no: Optional[str] = None, all_records: bool = False):
|
||||
def get_return_receives(tracking_no: Optional[str] = None, all_records: bool = False):
|
||||
try:
|
||||
conn = get_return_db_conn()
|
||||
cur = conn.cursor()
|
||||
conditions, params = [], []
|
||||
if tracking_no and tracking_no.strip():
|
||||
conditions.append("regexp_replace(tracking_no, '[-[:space:]]', '', 'g') = %s")
|
||||
@@ -292,33 +283,27 @@ async def get_return_receives(tracking_no: Optional[str] = None, all_records: bo
|
||||
elif not all_records:
|
||||
conditions.append("receive_date::text >= to_char(CURRENT_DATE - INTERVAL '3 months', 'YYYY-MM-DD')")
|
||||
where = ' WHERE ' + ' AND '.join(conditions) if conditions else ''
|
||||
cur.execute("SELECT * FROM return_receivings" + where + " ORDER BY receive_date DESC, mall ASC, id DESC", params)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
with closing(get_return_db_conn()) as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM return_receivings" + where + " ORDER BY receive_date DESC, mall ASC, id DESC", params)
|
||||
rows = cur.fetchall()
|
||||
return {"success": True, "data": [dict(r) for r in rows]}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
@router.delete("/request/{item_id}")
|
||||
async def delete_return_request(item_id: int):
|
||||
def delete_return_request(item_id: int):
|
||||
try:
|
||||
conn = get_return_db_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute("DELETE FROM return_requests WHERE id = %s", (item_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
with closing(get_return_db_conn()) as conn, conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM return_requests WHERE id = %s", (item_id,))
|
||||
return {"success": True}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.delete("/receive/{item_id}")
|
||||
async def delete_return_receive(item_id: int):
|
||||
def delete_return_receive(item_id: int):
|
||||
try:
|
||||
conn = get_return_db_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute("DELETE FROM return_receivings WHERE id = %s", (item_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
with closing(get_return_db_conn()) as conn, conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM return_receivings WHERE id = %s", (item_id,))
|
||||
return {"success": True}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
+29
-24
@@ -12,7 +12,8 @@
|
||||
const response = await origFetch(input, init);
|
||||
if (response.status === 401) {
|
||||
// 세션 만료 — dbx-main 로그인으로 위임 (next 로 현재 위치 보존)
|
||||
const next = encodeURIComponent((APP_BASE_PATH || '') + window.location.pathname + window.location.search);
|
||||
// pathname 에 이미 /corm 이 들어 있으므로 APP_BASE_PATH 를 다시 붙이지 않는다.
|
||||
const next = encodeURIComponent(window.location.pathname + window.location.search);
|
||||
window.location.href = (APP_BASE_PATH || '') + '/login?next=' + next;
|
||||
}
|
||||
return response;
|
||||
@@ -98,6 +99,16 @@ function formatShortDate(dateStr) {
|
||||
return `${m}월 ${day}일(${dow})`;
|
||||
}
|
||||
|
||||
// 서버·쇼핑몰에서 온 값(고객명, 주소, 비고 등)을 innerHTML에 넣기 전에 반드시 거친다.
|
||||
function escapeHtml(str) {
|
||||
return String(str == null ? '' : str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const ORDER_TYPE_LABELS = { noolak: '누락', pason: '파손', bullyang: '불량', misdelivery: '오배송', normal: '수동발주', ellen: '엘렌' };
|
||||
const SPECIAL_ORDER_TYPES = new Set(['noolak', 'pason', 'bullyang', 'misdelivery']);
|
||||
@@ -422,15 +433,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
return String(str == null ? '' : str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function resetMilkrunResult() {
|
||||
if (linesTbody) linesTbody.innerHTML = '';
|
||||
if (linesInfo) linesInfo.textContent = '';
|
||||
@@ -2843,6 +2845,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.duplicates && data.duplicates.length) {
|
||||
alert(`${data.count}건 등록했습니다.\n이미 입고된 송장 ${data.duplicates.length}건은 건너뛰었습니다:\n${data.duplicates.join('\n')}`);
|
||||
}
|
||||
bulkReceiveModal.style.display = 'none';
|
||||
bulkTrackingNumbers.value = '';
|
||||
updateBulkTrackingLineNumbers();
|
||||
@@ -2906,7 +2911,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const isReceived = item.is_received;
|
||||
const tr = document.createElement('tr');
|
||||
tr.style.cursor = 'pointer';
|
||||
let displayRemarks = item.remarks || '';
|
||||
let displayRemarks = escapeHtml(item.remarks || '');
|
||||
if (isReceived) {
|
||||
tr.style.textDecoration = 'line-through';
|
||||
tr.style.color = '#a0aec0';
|
||||
@@ -2928,16 +2933,16 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
if (item.request_date && !item.request_date.startsWith(todayStr)) {
|
||||
tr.style.backgroundColor = '#cbd5e0';
|
||||
}
|
||||
const rowDataJson = JSON.stringify(item).replace(/'/g, "'").replace(/"/g, """);
|
||||
const rowDataJson = escapeHtml(JSON.stringify(item));
|
||||
tr.innerHTML = `
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; width: 30px;" onclick="event.stopPropagation();">
|
||||
<input type="checkbox" class="chk-req-row" data-item="${rowDataJson}" ${isReceived ? 'disabled' : ''}>
|
||||
</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 100px;">${formatShortDate(item.request_date)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; cursor: pointer; white-space: nowrap; width: 90px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('이름이 복사되었습니다.');" title="클릭하여 복사">${item.receiver_name}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 130px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('연락처가 복사되었습니다.');" title="클릭하여 복사">${item.phone}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 110px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('송장번호가 복사되었습니다.');" title="클릭하여 복사">${item.tracking_no}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 65px;">${item.request_type}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 100px;">${escapeHtml(formatShortDate(item.request_date))}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; cursor: pointer; white-space: nowrap; width: 90px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('이름이 복사되었습니다.');" title="클릭하여 복사">${escapeHtml(item.receiver_name)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 130px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('연락처가 복사되었습니다.');" title="클릭하여 복사">${escapeHtml(item.phone)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 110px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('송장번호가 복사되었습니다.');" title="클릭하여 복사">${escapeHtml(item.tracking_no)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 65px;">${escapeHtml(item.request_type)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; width: 215px;">${displayRemarks}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; width: 40px;" onclick="event.stopPropagation();">
|
||||
<button class="btn-delete-req" data-id="${item.id}" style="background:none; border:none; color:red; cursor:pointer;">✕</button>
|
||||
@@ -3023,13 +3028,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const isCompleted = (item.receive_status === '환불완료' || item.receive_status === '교환완료');
|
||||
const statusStyle = isCompleted ? 'color: #e53e3e; font-weight: bold;' : '';
|
||||
tr.innerHTML = `
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 100px;">${formatShortDate(item.receive_date)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; cursor: pointer; white-space: nowrap; width: 90px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('이름이 복사되었습니다.');" title="클릭하여 복사">${item.receiver_name}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 130px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('연락처가 복사되었습니다.');" title="클릭하여 복사">${item.phone}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 110px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('송장번호가 복사되었습니다.');" title="클릭하여 복사">${item.tracking_no}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 85px;">${item.mall || ''}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 65px; ${statusStyle}">${item.receive_status}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; width: 160px;">${(item.remarks || '').replace(/맞교환/g, `<span style=\"color: red;\">맞교환</span>`)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 100px;">${escapeHtml(formatShortDate(item.receive_date))}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; cursor: pointer; white-space: nowrap; width: 90px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('이름이 복사되었습니다.');" title="클릭하여 복사">${escapeHtml(item.receiver_name)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 130px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('연락처가 복사되었습니다.');" title="클릭하여 복사">${escapeHtml(item.phone)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; cursor: pointer; white-space: nowrap; width: 110px;" onclick="navigator.clipboard.writeText(this.innerText); showToast('송장번호가 복사되었습니다.');" title="클릭하여 복사">${escapeHtml(item.tracking_no)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 85px;">${escapeHtml(item.mall)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; white-space: nowrap; width: 65px; ${statusStyle}">${escapeHtml(item.receive_status)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: left; width: 160px;">${escapeHtml(item.remarks).replace(/맞교환/g, `<span style=\"color: red;\">맞교환</span>`)}</td>
|
||||
<td style="padding: 8px; border-bottom: 1px solid #e2e8f0; text-align: center; width: 40px;" onclick="event.stopPropagation();">
|
||||
<button class="btn-delete-rec" data-id="${item.id}" style="background:none; border:none; color:red; cursor:pointer;">✕</button>
|
||||
</td>
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<link rel="stylesheet" href="{{ root_path }}/static/css/cs_records.css?v=21" />
|
||||
<link rel="stylesheet" href="{{ root_path }}/static/css/return_filters.css?v=1" />
|
||||
<link rel="stylesheet" href="{{ root_path }}/static/css/manual_grid.css?v=2" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.6/Sortable.min.js"></script>
|
||||
<script>
|
||||
// 서브경로 호스팅 정보 — JS 가 fetch 시 prefix 로 사용한다.
|
||||
window.APP_BASE_PATH = "{{ root_path }}";
|
||||
@@ -4030,7 +4030,7 @@
|
||||
{% include 'version_history.html' %}
|
||||
</main>
|
||||
</div>
|
||||
<script src="{{ root_path }}/static/js/app.js?v=73"></script>
|
||||
<script src="{{ root_path }}/static/js/app.js?v=74"></script>
|
||||
<script src="{{ root_path }}/static/js/manual_grid.js?v=2"></script>
|
||||
<script src="{{ root_path }}/static/js/cs_records.js?v=19"></script>
|
||||
<script src="{{ root_path }}/static/js/mall_event.js?v=7"></script>
|
||||
|
||||
Reference in New Issue
Block a user