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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 16:07:53 +09:00
parent 065e81bf97
commit d2fdec5c43
18 changed files with 5608 additions and 253 deletions
+3
View File
@@ -37,3 +37,6 @@ deploy.ps1
start.bat start.bat
test.ps1 test.ps1
*.xlsx *.xlsx
# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache)
.cache/
+17
View File
@@ -66,3 +66,20 @@ INTERNAL_SERVICE_TOKEN=__paste-same-value-as-dbx-orderlist__
# ============================================ # ============================================
POSTGRES_NETWORK=postgres_default POSTGRES_NETWORK=postgres_default
WEB_NETWORK=npm_default WEB_NETWORK=npm_default
# ============================================
# v9.1 선택 항목 (없으면 기본값)
# ============================================
# CS 기록 DB — 비우면 위 POSTGRES_* 와 ITEMCODE_DB 를 쓴다
# CS_RECORD_DB_HOST=
# CS_RECORD_DB_PORT=
# CS_RECORD_DB_NAME=
# CS_RECORD_DB_USER=
# CS_RECORD_DB_PASSWORD=
# CS 기록 다음 업무일 계산에 더할 휴일(YYYY-MM-DD, 쉼표 구분)
# CS_RECORD_EXTRA_HOLIDAYS=
# 구글 연동 시간 제한(초)·동시 작업 수, 설정 시트 캐시 유효 시간(초)
# GOOGLE_CONNECT_TIMEOUT=3
# GOOGLE_READ_TIMEOUT=10
# GOOGLE_WORKERS=4
# SETTINGS_CACHE_TTL=60
+3
View File
@@ -44,3 +44,6 @@ deploy.bat
deploy.ps1 deploy.ps1
start.bat start.bat
test.ps1 test.ps1
# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache)
.cache/
+8 -1
View File
@@ -18,12 +18,19 @@ FastAPI + PostgreSQL 기반, Docker로 실행.
| DB 이름 | 용도 | | DB 이름 | 용도 |
|---|---| |---|---|
| `itemcode_db` | 품목코드 마스터 | | `itemcode_db` | 품목코드 마스터 + CS 기록(v9.1: `cs_records`·`cs_memo_folders`·`cs_permanent_memos`·`cs_schedules`, 앱이 처음 쓸 때 `CREATE TABLE IF NOT EXISTS` 로 자동 생성) |
| `orderlist_db` | 주문 정보 조회 | | `orderlist_db` | 주문 정보 조회 |
| `return_db` | 반품 데이터 저장 | | `return_db` | 반품 데이터 저장 |
모두 DB 계정은 `king` 통일. 모두 DB 계정은 `king` 통일.
## 버전
- 현재 **v9.1** (2026.09.03) — CS 기록 메뉴(달력·상시 메모·일정, 엑셀 내려받기/업로드), New CS 누락·파손·불량·오배송 발주 → CS 기록 자동 저장,
반품 신청/입고 목록 최근 3개월 + 원송장번호 전체 검색, 구글 연동 시간 제한·설정 스냅샷(`google_runtime.py`).
- 원본은 로컬 `CS 통합 프로그램` 폴더. 서버판은 원본 위에 SSO(AuthGuard)·`/corm` 서브경로·환경변수 DB 설정·`/health/db` 를 유지한다.
원본을 다시 가져올 때 이 부분과 `cafe24_api.py`·`naver_api.py`(원본은 키가 코드에 박혀 있음 — 서버판은 환경변수)는 덮어쓰지 않는다.
--- ---
## 서버 배포 절차 (`/opt/dbx-corm`) ## 서버 배포 절차 (`/opt/dbx-corm`)
+243
View File
@@ -0,0 +1,243 @@
"""Bounded Google I/O and last-known-good settings, independent of the ASGI loop."""
import asyncio
import copy
import functools
import json
import logging
import os
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import requests
from fastapi import HTTPException
from google.auth.transport.requests import AuthorizedSession, Request
logger = logging.getLogger(__name__)
GOOGLE_CONNECT_TIMEOUT = float(os.getenv("GOOGLE_CONNECT_TIMEOUT", "3"))
GOOGLE_READ_TIMEOUT = float(os.getenv("GOOGLE_READ_TIMEOUT", "10"))
GOOGLE_TIMEOUT = (GOOGLE_CONNECT_TIMEOUT, GOOGLE_READ_TIMEOUT)
GOOGLE_WORKERS = max(1, int(os.getenv("GOOGLE_WORKERS", "4")))
_executor = ThreadPoolExecutor(max_workers=GOOGLE_WORKERS, thread_name_prefix="google-io")
_slots = threading.BoundedSemaphore(GOOGLE_WORKERS)
_settings_write_lock = threading.RLock()
_history_lock = threading.RLock()
def _bounded_timeout(timeout):
if timeout is None:
return GOOGLE_TIMEOUT
if isinstance(timeout, tuple):
connect, read = timeout
else:
connect = read = timeout
return (
min(connect, GOOGLE_CONNECT_TIMEOUT) if connect is not None else GOOGLE_CONNECT_TIMEOUT,
min(read, GOOGLE_READ_TIMEOUT) if read is not None else GOOGLE_READ_TIMEOUT,
)
class GoogleTimeoutSession(requests.Session):
"""Also bound token refresh calls, which otherwise default to 120 seconds."""
def request(self, method, url, **kwargs):
kwargs["timeout"] = _bounded_timeout(kwargs.get("timeout"))
return super().request(method, url, **kwargs)
class GoogleAuthorizedSession(AuthorizedSession):
def request(self, method, url, **kwargs):
kwargs["timeout"] = _bounded_timeout(kwargs.get("timeout"))
return super().request(method, url, **kwargs)
def create_google_session(credentials):
return GoogleAuthorizedSession(
credentials,
auth_request=Request(session=GoogleTimeoutSession()),
refresh_timeout=GOOGLE_CONNECT_TIMEOUT + GOOGLE_READ_TIMEOUT,
)
def create_google_client(credentials):
import gspread
client = gspread.Client(auth=credentials, session=create_google_session(credentials))
client.set_timeout(GOOGLE_TIMEOUT)
return client
async def run_google_io(function, *args, **kwargs):
# No unbounded executor queue, and no consumption of FastAPI's DB worker pool.
if not _slots.acquire(blocking=False):
raise HTTPException(
status_code=503,
detail="구글 연동 작업이 진행 중입니다. 잠시 후 다시 시도해주세요.",
headers={"Retry-After": "3"},
)
try:
future = _executor.submit(functools.partial(function, *args, **kwargs))
except BaseException:
_slots.release()
raise
future.add_done_callback(lambda _: _slots.release())
# Disconnecting the browser must not free a slot while its write still runs.
return await asyncio.shield(asyncio.wrap_future(future))
def google_worker(function):
@functools.wraps(function)
async def wrapped(*args, **kwargs):
return await run_google_io(function, *args, **kwargs)
return wrapped
def _serialized(lock):
def decorate(function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
with lock:
return function(*args, **kwargs)
return wrapped
return decorate
settings_update = _serialized(_settings_write_lock)
history_access = _serialized(_history_lock)
class SettingsCache:
"""Serve snapshots immediately; refresh stale data once, in a separate worker."""
def __init__(self, path, spreadsheet_id, ttl=60, retry_delay=15):
self.path = Path(path)
self.spreadsheet_id = spreadsheet_id
self.ttl = ttl
self.retry_delay = retry_delay
self._lock = threading.RLock()
self._refresh_lock = threading.Lock()
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="settings-refresh")
self._pending = None
self._rows = None
self._loaded_at = float("-inf")
self._retry_at = 0.0
self._generation = 0
self._restore()
@property
def has_value(self):
with self._lock:
return self._rows is not None
@property
def stale(self):
with self._lock:
return time.monotonic() - self._loaded_at >= self.ttl
def _restore(self):
try:
payload = json.loads(self.path.read_text(encoding="utf-8"))
rows = payload["rows"]
if payload["spreadsheet_id"] != self.spreadsheet_id:
return
if not isinstance(rows, list) or not all(
isinstance(row, list) and all(isinstance(cell, str) for cell in row)
for row in rows
):
return
self._rows = rows
# A restored snapshot is usable immediately, but always revalidated.
except (OSError, ValueError, KeyError, TypeError):
pass
def _persist_locked(self):
temporary = None
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=self.path.parent, delete=False
) as target:
temporary = target.name
json.dump(
{"spreadsheet_id": self.spreadsheet_id, "rows": self._rows},
target, ensure_ascii=False,
)
os.replace(temporary, self.path)
except OSError as exc:
logger.warning("Settings snapshot persistence failed (%s)", type(exc).__name__)
finally:
if temporary and os.path.exists(temporary):
os.unlink(temporary)
def publish(self, rows):
with self._lock:
self._rows = copy.deepcopy(rows)
self._loaded_at = time.monotonic()
self._retry_at = 0.0
self._generation += 1
self._persist_locked()
def invalidate(self):
with self._lock:
self._loaded_at = float("-inf")
self._retry_at = 0.0
self._generation += 1
def _load(self, loader, force=False):
with self._refresh_lock:
with self._lock:
if not force:
if self._rows is not None and not self.stale:
return copy.deepcopy(self._rows)
if time.monotonic() < self._retry_at:
if self._rows is not None:
return copy.deepcopy(self._rows)
raise RuntimeError("Settings refresh is cooling down")
generation = self._generation
try:
rows = loader()
except Exception:
with self._lock:
self._retry_at = time.monotonic() + self.retry_delay
raise
with self._lock:
# An earlier read must never replace a subsequently saved setting.
if generation == self._generation:
self.publish(rows)
return copy.deepcopy(self._rows)
def _background_load(self, loader):
try:
self._load(loader)
except Exception as exc:
# Do not log URLs, credential contents or settings data.
logger.warning("Google settings refresh failed (%s); retaining snapshot", type(exc).__name__)
def refresh_in_background(self, loader):
with self._lock:
if time.monotonic() < self._retry_at:
return
if self._pending is None or self._pending.done():
self._pending = self._executor.submit(self._background_load, loader)
def read(self, loader, force=False):
if force:
# Editors must not overwrite Google using a stale cached snapshot.
return self._load(loader, force=True)
with self._lock:
if self._rows is not None:
rows = copy.deepcopy(self._rows)
if self.stale:
self.refresh_in_background(loader)
return rows
return self._load(loader)
def close(self):
self._executor.shutdown(wait=True)
+134 -104
View File
@@ -10,11 +10,11 @@ import io
import math import math
import datetime import datetime
import configparser import configparser
import threading
import urllib.request import urllib.request
import urllib.parse import urllib.parse
import uuid import uuid
import secrets import secrets
import threading
from urllib.parse import quote from urllib.parse import quote
from dotenv import load_dotenv from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks
@@ -32,6 +32,10 @@ from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates from fastapi.templating import Jinja2Templates
from pydantic import BaseModel from pydantic import BaseModel
from typing import List, Optional, Dict, Any from typing import List, Optional, Dict, Any
from google_runtime import (
GOOGLE_READ_TIMEOUT, GoogleTimeoutSession, SettingsCache,
create_google_client, google_worker, history_access, run_google_io, settings_update,
)
# ========================================== # ==========================================
# SSO / 서브경로 호스팅 설정 # SSO / 서브경로 호스팅 설정
@@ -213,6 +217,9 @@ app.include_router(coupang_milkrun_router)
from routers.mall_event import router as mall_event_router from routers.mall_event import router as mall_event_router
app.include_router(mall_event_router) app.include_router(mall_event_router)
from routers.cs_records import router as cs_records_router, add_special_order_records
app.include_router(cs_records_router)
# Ensure directories exist # Ensure directories exist
os.makedirs("static/css", exist_ok=True) os.makedirs("static/css", exist_ok=True)
os.makedirs("static/js", exist_ok=True) os.makedirs("static/js", exist_ok=True)
@@ -230,6 +237,11 @@ MANUAL_SPREADSHEET_ID = os.getenv('MANUAL_SPREADSHEET_ID', '1QxFtjDurPPZd8NmtXBy
SETTINGS_SPREADSHEET_ID = os.getenv('SETTINGS_SPREADSHEET_ID', '1k7SNEdIaRtGXzQNdJSQAiNSDRwzOePDRTLHY_mNCO8M') SETTINGS_SPREADSHEET_ID = os.getenv('SETTINGS_SPREADSHEET_ID', '1k7SNEdIaRtGXzQNdJSQAiNSDRwzOePDRTLHY_mNCO8M')
MANUAL_HISTORY_FILE = os.getenv('MANUAL_HISTORY_FILE', os.path.join(BASE_DIR, 'manual_history.dat')) MANUAL_HISTORY_FILE = os.getenv('MANUAL_HISTORY_FILE', os.path.join(BASE_DIR, 'manual_history.dat'))
SMS_HISTORY_HEADERS = ["일시", "주문유형", "입금액", "주문아이템", "메시지 내용", "이름", "연락처", "주소"] SMS_HISTORY_HEADERS = ["일시", "주문유형", "입금액", "주문아이템", "메시지 내용", "이름", "연락처", "주소"]
_settings_cache = SettingsCache(
os.getenv("SETTINGS_CACHE_FILE", os.path.join(BASE_DIR, ".cache", "settings.json")),
SETTINGS_SPREADSHEET_ID,
ttl=float(os.getenv("SETTINGS_CACHE_TTL", "60")),
)
def env_bool(name: str, default: bool = False) -> bool: def env_bool(name: str, default: bool = False) -> bool:
raw = os.getenv(name) raw = os.getenv(name)
@@ -264,38 +276,21 @@ def load_service_account_credentials(scopes):
) )
# ----- Utility Functions ----- # ----- Utility Functions -----
def read_config(force_refresh=False): def _load_settings_rows():
global _CONFIG_ROWS_CACHE, _CONFIG_ROWS_CACHE_TIME return get_settings_worksheet().get_all_values()
def read_config(force_refresh=False):
config = configparser.ConfigParser(allow_no_value=True) config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str config.optionxform = str
rows = []
# 1. 캐시 유효성 판단 (force_refresh 가 아니고, 캐시가 존재하며, TTL 이 지나지 않은 경우)
if not force_refresh and _CONFIG_ROWS_CACHE is not None:
if time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL:
rows = _CONFIG_ROWS_CACHE
# 2. 캐시가 없거나 만료된 경우 구글 시트에서 직접 새로 로드
if not rows:
with _CONFIG_LOCK:
# 락 대기 중 다른 스레드가 캐시를 갱신했을 수 있으므로 다시 검사 (Double-Checked Locking)
if not force_refresh and _CONFIG_ROWS_CACHE is not None and time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL:
rows = _CONFIG_ROWS_CACHE
else:
for _ in range(3):
try: try:
ws = get_settings_worksheet() rows = _settings_cache.read(_load_settings_rows, force=force_refresh)
rows = ws.get_all_values() except Exception as exc:
break raise HTTPException(
except Exception as e: status_code=503,
time.sleep(1.5) detail="구글에서 최신 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.",
print(f"Google Sheets 불러오기 재시도 중...: {e}") ) from exc
if rows:
_CONFIG_ROWS_CACHE = rows
_CONFIG_ROWS_CACHE_TIME = time.time()
if rows and len(rows) > 1: if rows and len(rows) > 1:
for row in rows: for row in rows:
@@ -320,11 +315,9 @@ def read_config(force_refresh=False):
config.set(section, key, val) config.set(section, key, val)
else: else:
config.set(section, key) config.set(section, key)
config.set(section, key)
return config return config
def write_config(config): def write_config(config):
global _CONFIG_ROWS_CACHE, _CONFIG_ROWS_CACHE_TIME
rows = [["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]] rows = [["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]]
for section in config.sections(): for section in config.sections():
items = config.items(section) items = config.items(section)
@@ -338,23 +331,35 @@ def write_config(config):
v_parts = [p.strip() for p in v.split("|")] v_parts = [p.strip() for p in v.split("|")]
rows.append([section, k] + v_parts) rows.append([section, k] + v_parts)
for attempt in range(3):
try: try:
ws = get_settings_worksheet() ws = get_settings_worksheet()
ws.clear() requests = []
ws.update(values=rows) column_count = max(len(row) for row in rows)
if len(rows) > ws.row_count or column_count > ws.col_count:
# 구글 시트에 저장이 성공하면 로컬 캐시도 즉시 최신화 requests.append({"updateSheetProperties": {
with _CONFIG_LOCK: "properties": {"sheetId": ws.id, "gridProperties": {
_CONFIG_ROWS_CACHE = rows "rowCount": max(len(rows), ws.row_count),
_CONFIG_ROWS_CACHE_TIME = time.time() "columnCount": max(column_count, ws.col_count),
return }},
except Exception as e: "fields": "gridProperties(rowCount,columnCount)",
print(f"Google Sheets 저장 시도 {attempt+1}/3 실패: {e}") }})
time.sleep(1.5) # One atomic request replaces values and clears old trailing cells. A
# timeout between separate clear/update requests must not erase settings.
print("Google Sheets에 설정을 저장하는 데 최종 실패했습니다.") requests.append({"updateCells": {
raise Exception("구글 시트 연동 오류 (할당량 초과). 잠시 후 다시 시도해주세요.") "range": {"sheetId": ws.id},
"rows": [{"values": [
{"userEnteredValue": {"stringValue": str(cell)}} for cell in row
]} for row in rows],
"fields": "userEnteredValue",
}})
ws.spreadsheet.batch_update({"requests": requests})
except Exception as exc:
_settings_cache.invalidate()
raise HTTPException(
status_code=503,
detail="설정 저장 응답을 확인하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.",
) from exc
_settings_cache.publish(rows)
# ----- API Endpoints ----- # ----- API Endpoints -----
@@ -380,21 +385,17 @@ async def index(request: Request):
@app.get("/api/config") @app.get("/api/config")
async def get_config(): async def get_config():
if _settings_cache.has_value:
config = read_config() config = read_config()
else:
config = await run_google_io(read_config)
data = {} data = {}
for section in config.sections(): for section in config.sections():
data[section] = dict(config.items(section)) data[section] = dict(config.items(section))
data[section]["__order"] = list(config.options(section)) data[section]["__order"] = list(config.options(section))
return JSONResponse(data) return JSONResponse(data, headers={
"X-Settings-Cache": "stale" if _settings_cache.stale else "fresh",
@app.post("/api/config/refresh") })
async def refresh_config():
"""구글 시트로부터 실시간으로 설정을 동기화하여 캐시를 강제 갱신합니다."""
try:
read_config(force_refresh=True)
return {"status": "success", "message": "설정 캐시가 성공적으로 갱신되었습니다."}
except Exception as e:
raise HTTPException(status_code=500, detail=f"설정 캐시 갱신 실패: {str(e)}")
@@ -423,8 +424,10 @@ class SubgroupNamePayload(BaseModel):
name: str = "" name: str = ""
@app.post("/api/products/settings") @app.post("/api/products/settings")
async def save_products_settings(payload: ProductsPayload): @google_worker
config = read_config() @settings_update
def save_products_settings(payload: ProductsPayload):
config = read_config(force_refresh=True)
if config.has_section("GROUP_NAMES"): if config.has_section("GROUP_NAMES"):
config.remove_section("GROUP_NAMES") config.remove_section("GROUP_NAMES")
@@ -461,7 +464,9 @@ async def save_products_settings(payload: ProductsPayload):
return {"status": "success"} return {"status": "success"}
@app.post("/api/products/subgroup-name") @app.post("/api/products/subgroup-name")
async def save_product_subgroup_name(payload: SubgroupNamePayload): @google_worker
@settings_update
def save_product_subgroup_name(payload: SubgroupNamePayload):
group_key = payload.group_key.strip() group_key = payload.group_key.strip()
subgroup_index = payload.subgroup_index subgroup_index = payload.subgroup_index
subgroup_name = payload.name.strip() subgroup_name = payload.name.strip()
@@ -471,7 +476,7 @@ async def save_product_subgroup_name(payload: SubgroupNamePayload):
if len(subgroup_name) > 40: if len(subgroup_name) > 40:
raise HTTPException(status_code=400, detail="그룹 이름은 40자 이내로 입력해주세요.") raise HTTPException(status_code=400, detail="그룹 이름은 40자 이내로 입력해주세요.")
config = read_config() config = read_config(force_refresh=True)
if not config.has_section(group_key): if not config.has_section(group_key):
raise HTTPException(status_code=404, detail="상품 분류를 찾을 수 없습니다.") raise HTTPException(status_code=404, detail="상품 분류를 찾을 수 없습니다.")
if not config.has_section("SUBGROUP_NAMES"): if not config.has_section("SUBGROUP_NAMES"):
@@ -526,31 +531,20 @@ def format_phone_number(num_str):
# ----- Google Sheets Global Cache ----- # Each Google worker owns its requests session and worksheet handles.
# ----- Google Sheets Config Cache ----- _google_state = threading.local()
_CONFIG_ROWS_CACHE = None
_CONFIG_ROWS_CACHE_TIME = 0.0
_CONFIG_LOCK = threading.Lock()
CONFIG_CACHE_TTL = 600.0 # 캐시 유효 시간: 10분
gs_client_global = None
worksheet_manual_global = None
worksheet_settings_global = None
worksheet_sms_history_global = None
worksheet_manual_history_global = None
def get_gspread_client(): def get_gspread_client():
global gs_client_global
if gspread is None: if gspread is None:
raise Exception("gspread 라이브러리가 없습니다.") raise Exception("gspread 라이브러리가 없습니다.")
if gs_client_global is None: if getattr(_google_state, "client", None) is None:
scopes = ['https://www.googleapis.com/auth/spreadsheets'] scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds = load_service_account_credentials(scopes) creds = load_service_account_credentials(scopes)
gs_client_global = gspread.authorize(creds) _google_state.client = create_google_client(creds)
return gs_client_global return _google_state.client
def get_manual_worksheet(): def get_manual_worksheet():
global worksheet_manual_global worksheet_manual_global = getattr(_google_state, 'manual', None)
if worksheet_manual_global is None: if worksheet_manual_global is None:
client = get_gspread_client() client = get_gspread_client()
ss = client.open_by_key(MANUAL_SPREADSHEET_ID) ss = client.open_by_key(MANUAL_SPREADSHEET_ID)
@@ -561,10 +555,11 @@ def get_manual_worksheet():
except Exception: except Exception:
pass pass
worksheet_manual_global = ws worksheet_manual_global = ws
_google_state.manual = worksheet_manual_global
return worksheet_manual_global return worksheet_manual_global
def get_settings_worksheet(): def get_settings_worksheet():
global worksheet_settings_global worksheet_settings_global = getattr(_google_state, 'settings', None)
if worksheet_settings_global is None: if worksheet_settings_global is None:
client = get_gspread_client() client = get_gspread_client()
ss = client.open_by_key(SETTINGS_SPREADSHEET_ID) ss = client.open_by_key(SETTINGS_SPREADSHEET_ID)
@@ -572,10 +567,11 @@ def get_settings_worksheet():
worksheet_settings_global = ss.worksheet("설정") worksheet_settings_global = ss.worksheet("설정")
except gspread.exceptions.WorksheetNotFound: except gspread.exceptions.WorksheetNotFound:
worksheet_settings_global = ss.add_worksheet(title="설정", rows=500, cols=3) worksheet_settings_global = ss.add_worksheet(title="설정", rows=500, cols=3)
_google_state.settings = worksheet_settings_global
return worksheet_settings_global return worksheet_settings_global
def get_sms_history_worksheet(): def get_sms_history_worksheet():
global worksheet_sms_history_global worksheet_sms_history_global = getattr(_google_state, 'sms_history', None)
if worksheet_sms_history_global is None: if worksheet_sms_history_global is None:
client = get_gspread_client() client = get_gspread_client()
ss = client.open_by_key(SETTINGS_SPREADSHEET_ID) ss = client.open_by_key(SETTINGS_SPREADSHEET_ID)
@@ -587,10 +583,11 @@ def get_sms_history_worksheet():
worksheet_sms_history_global.add_cols(len(SMS_HISTORY_HEADERS) - worksheet_sms_history_global.col_count) worksheet_sms_history_global.add_cols(len(SMS_HISTORY_HEADERS) - worksheet_sms_history_global.col_count)
if worksheet_sms_history_global.row_values(1)[:len(SMS_HISTORY_HEADERS)] != SMS_HISTORY_HEADERS: if worksheet_sms_history_global.row_values(1)[:len(SMS_HISTORY_HEADERS)] != SMS_HISTORY_HEADERS:
worksheet_sms_history_global.update(values=[SMS_HISTORY_HEADERS], range_name="A1:H1", value_input_option='USER_ENTERED') worksheet_sms_history_global.update(values=[SMS_HISTORY_HEADERS], range_name="A1:H1", value_input_option='USER_ENTERED')
_google_state.sms_history = worksheet_sms_history_global
return worksheet_sms_history_global return worksheet_sms_history_global
def get_manual_history_worksheet(): def get_manual_history_worksheet():
global worksheet_manual_history_global worksheet_manual_history_global = getattr(_google_state, 'manual_history', None)
if worksheet_manual_history_global is None: if worksheet_manual_history_global is None:
client = get_gspread_client() client = get_gspread_client()
ss = client.open_by_key(SETTINGS_SPREADSHEET_ID) ss = client.open_by_key(SETTINGS_SPREADSHEET_ID)
@@ -599,6 +596,7 @@ def get_manual_history_worksheet():
except gspread.exceptions.WorksheetNotFound: except gspread.exceptions.WorksheetNotFound:
worksheet_manual_history_global = ss.add_worksheet(title="수동발주내역", rows=1000, cols=3) worksheet_manual_history_global = ss.add_worksheet(title="수동발주내역", rows=1000, cols=3)
worksheet_manual_history_global.append_row(["일시", "고객명", "주문금액"]) worksheet_manual_history_global.append_row(["일시", "고객명", "주문금액"])
_google_state.manual_history = worksheet_manual_history_global
return worksheet_manual_history_global return worksheet_manual_history_global
@app.on_event("startup") @app.on_event("startup")
@@ -619,18 +617,12 @@ async def startup_event():
if env_bool("SKIP_GOOGLE_INIT", False): if env_bool("SKIP_GOOGLE_INIT", False):
print("SKIP_GOOGLE_INIT=1 이므로 구글 시트 선초기화를 건너뜁니다.") print("SKIP_GOOGLE_INIT=1 이므로 구글 시트 선초기화를 건너뜁니다.")
else: else:
try: # Google unavailability must not delay startup or the DB-backed tabs.
print("구글 시트 연동 초기화 중...") _settings_cache.refresh_in_background(_load_settings_rows)
get_manual_worksheet()
get_settings_worksheet()
get_sms_history_worksheet()
get_manual_history_worksheet()
print("구글 시트 연동 완료!")
except Exception as e:
print(f"구글 시트 연동 초기화 실패 (사용 전 권한을 확인하세요): {str(e)}")
@app.post("/api/order/submit") @app.post("/api/order/submit")
async def submit_order_submit(payload: OrderPayload): @google_worker
def submit_order_submit(payload: OrderPayload):
date_str, time_str, current_datetime_str = get_current_time_info() date_str, time_str, current_datetime_str = get_current_time_info()
c_tel = format_phone_number(payload.phone) c_tel = format_phone_number(payload.phone)
@@ -665,7 +657,26 @@ async def submit_order_submit(payload: OrderPayload):
worksheet.append_rows(rows, value_input_option='USER_ENTERED') worksheet.append_rows(rows, value_input_option='USER_ENTERED')
clipboard_text = "\r\n".join(lines) + "\r\n" clipboard_text = "\r\n".join(lines) + "\r\n"
return {"status": "success", "message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.", "clipboard_text": clipboard_text, "timestamp": current_datetime_str} cs_record_saved_count = 0
cs_record_warning = ""
if order_status and lines:
try:
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
record_date = datetime.datetime.now(korea_tz).date()
event_key = f"{uuid.uuid4()}"
cs_record_saved_count = add_special_order_records(record_date, lines, event_key)
except Exception as cs_record_error:
cs_record_warning = "발주 입력은 완료됐지만 CS 기록 자동 저장에 실패했습니다."
print(f"CS 기록 자동 저장 실패: {cs_record_error}")
return {
"status": "success",
"message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.",
"clipboard_text": clipboard_text,
"timestamp": current_datetime_str,
"cs_record_saved_count": cs_record_saved_count,
"cs_record_warning": cs_record_warning,
}
except Exception as e: except Exception as e:
err_str = str(e) err_str = str(e)
if not err_str or err_str.strip() == "{}": if not err_str or err_str.strip() == "{}":
@@ -673,13 +684,14 @@ async def submit_order_submit(payload: OrderPayload):
raise HTTPException(status_code=500, detail=f"수동발주 시트 접근 에러 (스프레드시트에 이메일 편집 권한을 추가했는지 확인해주세요!): {err_str}") raise HTTPException(status_code=500, detail=f"수동발주 시트 접근 에러 (스프레드시트에 이메일 편집 권한을 추가했는지 확인해주세요!): {err_str}")
@app.post("/api/sheet/download_and_clear") @app.post("/api/sheet/download_and_clear")
async def download_and_clear_sheet(): @google_worker
def download_and_clear_sheet():
try: try:
scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'] scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
creds = load_service_account_credentials(scopes) creds = load_service_account_credentials(scopes)
import google.auth.transport.requests import google.auth.transport.requests
request = google.auth.transport.requests.Request() request = google.auth.transport.requests.Request(session=GoogleTimeoutSession())
creds.refresh(request) creds.refresh(request)
access_token = creds.token access_token = creds.token
@@ -688,7 +700,7 @@ async def download_and_clear_sheet():
url = f"https://docs.google.com/spreadsheets/export?id={MANUAL_SPREADSHEET_ID}&exportFormat=xlsx" 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}"}) req = urllib.request.Request(url, headers={"Authorization": f"Bearer {access_token}"})
with urllib.request.urlopen(req) as response: with urllib.request.urlopen(req, timeout=GOOGLE_READ_TIMEOUT) as response:
content = response.read() content = response.read()
korea_tz = datetime.timezone(datetime.timedelta(hours=9)) korea_tz = datetime.timezone(datetime.timedelta(hours=9))
@@ -735,7 +747,9 @@ async def download_and_clear_sheet():
@app.get("/api/sms/history") @app.get("/api/sms/history")
async def get_history(): @google_worker
@history_access
def get_history():
local_history = {} local_history = {}
def merge_history_item(sheet_item, local_item): def merge_history_item(sheet_item, local_item):
if not local_item: if not local_item:
@@ -800,7 +814,9 @@ async def get_history():
return [] return []
@app.post("/api/sms/history") @app.post("/api/sms/history")
async def add_history(data: dict): @google_worker
@history_access
def add_history(data: dict):
with open(SMS_HISTORY_FILE, 'a', encoding='utf-8') as f: with open(SMS_HISTORY_FILE, 'a', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False) json.dump(data, f, ensure_ascii=False)
f.write('\n') f.write('\n')
@@ -839,7 +855,9 @@ async def add_history(data: dict):
return {"status": "success"} return {"status": "success"}
@app.delete("/api/sms/history") @app.delete("/api/sms/history")
async def clear_history(): @google_worker
@history_access
def clear_history():
if os.path.exists(SMS_HISTORY_FILE): if os.path.exists(SMS_HISTORY_FILE):
os.remove(SMS_HISTORY_FILE) os.remove(SMS_HISTORY_FILE)
@@ -852,7 +870,9 @@ async def clear_history():
return {"status": "success"} return {"status": "success"}
@app.delete("/api/sms/history/{index}") @app.delete("/api/sms/history/{index}")
async def delete_history_item(index: int): @google_worker
@history_access
def delete_history_item(index: int):
try: try:
ws = get_sms_history_worksheet() ws = get_sms_history_worksheet()
rows = ws.get_all_values() rows = ws.get_all_values()
@@ -887,7 +907,9 @@ async def delete_history_item(index: int):
import sys import sys
@app.get("/api/manual/history") @app.get("/api/manual/history")
async def get_manual_history(): @google_worker
@history_access
def get_manual_history():
korea_tz = datetime.timezone(datetime.timedelta(hours=9)) korea_tz = datetime.timezone(datetime.timedelta(hours=9))
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d") today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
@@ -933,7 +955,9 @@ async def get_manual_history():
return list(local_history.values()) return list(local_history.values())
@app.post("/api/manual/history") @app.post("/api/manual/history")
async def add_manual_history(data: dict): @google_worker
@history_access
def add_manual_history(data: dict):
local_history = [] local_history = []
korea_tz = datetime.timezone(datetime.timedelta(hours=9)) korea_tz = datetime.timezone(datetime.timedelta(hours=9))
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d") today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
@@ -970,7 +994,9 @@ async def add_manual_history(data: dict):
return {"status": "success"} return {"status": "success"}
@app.delete("/api/manual/history/{timestamp}") @app.delete("/api/manual/history/{timestamp}")
async def delete_manual_history(timestamp: str): @google_worker
@history_access
def delete_manual_history(timestamp: str):
# 구글 시트에서 삭제 # 구글 시트에서 삭제
try: try:
ws = get_manual_worksheet() ws = get_manual_worksheet()
@@ -1041,7 +1067,9 @@ async def get_fonts():
return fonts_list return fonts_list
@app.post("/api/gift/settings") @app.post("/api/gift/settings")
async def save_gift_settings(payload: dict): @google_worker
@settings_update
def save_gift_settings(payload: dict):
# 하위 호환성 (기존 rules만 오는 경우) # 하위 호환성 (기존 rules만 오는 경우)
if "rules" in payload: if "rules" in payload:
rules = payload["rules"] rules = payload["rules"]
@@ -1050,7 +1078,7 @@ async def save_gift_settings(payload: dict):
rules = payload rules = payload
app_settings = {} app_settings = {}
config = read_config() config = read_config(force_refresh=True)
section = "SMS_GIFT_RULES" section = "SMS_GIFT_RULES"
if section not in config: if section not in config:
config.add_section(section) config.add_section(section)
@@ -1075,8 +1103,10 @@ async def save_gift_settings(payload: dict):
return {"status": "success"} return {"status": "success"}
@app.post("/api/app/settings") @app.post("/api/app/settings")
async def save_app_settings(payload: dict): @google_worker
config = read_config() @settings_update
def save_app_settings(payload: dict):
config = read_config(force_refresh=True)
app_section = "APP_SETTINGS" app_section = "APP_SETTINGS"
if app_section not in config: if app_section not in config:
config.add_section(app_section) config.add_section(app_section)
+1
View File
@@ -13,3 +13,4 @@ requests
psycopg2-binary psycopg2-binary
python-dotenv python-dotenv
itsdangerous itsdangerous
holidays
+10 -7
View File
@@ -25,6 +25,7 @@ import requests
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
from pydantic import BaseModel from pydantic import BaseModel
from google_runtime import GOOGLE_READ_TIMEOUT, GOOGLE_TIMEOUT, create_google_client, create_google_session, google_worker
router = APIRouter(prefix="/api/coupang-milkrun", tags=["Coupang Milkrun"]) router = APIRouter(prefix="/api/coupang-milkrun", tags=["Coupang Milkrun"])
@@ -315,7 +316,7 @@ _sheet_tabs_cache = {} # file_id -> (저장시각, 시트 목록 응답)
# 구글이 응답을 안 주면 무한정 매달리지 않도록 (연결 대기, 응답 대기) 초 # 구글이 응답을 안 주면 무한정 매달리지 않도록 (연결 대기, 응답 대기) 초
_HTTP_TIMEOUT = (10, 120) _HTTP_TIMEOUT = (10, 120)
_HTTP_READ_TIMEOUT = 120 _HTTP_READ_TIMEOUT = GOOGLE_READ_TIMEOUT
# 밀크런 출고리스트 구글 시트 (화면에서 주소를 입력하지 않아도 되도록 기본값으로 둔다) # 밀크런 출고리스트 구글 시트 (화면에서 주소를 입력하지 않아도 되도록 기본값으로 둔다)
MILKRUN_SHEET_URL = os.getenv( MILKRUN_SHEET_URL = os.getenv(
@@ -419,7 +420,7 @@ def _drive_get(session, file_id, params):
return session.get( return session.get(
f"https://www.googleapis.com/drive/v3/files/{file_id}", f"https://www.googleapis.com/drive/v3/files/{file_id}",
params={**params, "supportsAllDrives": "true"}, params={**params, "supportsAllDrives": "true"},
timeout=60, timeout=GOOGLE_TIMEOUT,
) )
@@ -463,7 +464,7 @@ def _fetch_drive_workbook_authenticated(file_id):
except ImportError: except ImportError:
raise HTTPException(status_code=500, detail="google-auth 라이브러리가 설치되어 있지 않습니다.") raise HTTPException(status_code=500, detail="google-auth 라이브러리가 설치되어 있지 않습니다.")
session = AuthorizedSession(_load_credentials([DRIVE_SCOPE])) session = create_google_session(_load_credentials([DRIVE_SCOPE]))
response = _drive_get(session, file_id, {"alt": "media"}) response = _drive_get(session, file_id, {"alt": "media"})
if response.status_code != 200: if response.status_code != 200:
raise HTTPException(status_code=400, detail=_drive_error_detail(response)) raise HTTPException(status_code=400, detail=_drive_error_detail(response))
@@ -493,7 +494,7 @@ def fetch_drive_file_name(file_id):
try: try:
from google.auth.transport.requests import AuthorizedSession from google.auth.transport.requests import AuthorizedSession
session = AuthorizedSession(_load_credentials([DRIVE_SCOPE])) session = create_google_session(_load_credentials([DRIVE_SCOPE]))
response = _drive_get(session, file_id, {"fields": "name"}) response = _drive_get(session, file_id, {"fields": "name"})
if response.status_code == 200: if response.status_code == 200:
return response.json().get("name", "") return response.json().get("name", "")
@@ -548,7 +549,7 @@ def _read_sheet_tabs(file_id):
raise HTTPException(status_code=500, detail="gspread 라이브러리가 설치되어 있지 않습니다.") raise HTTPException(status_code=500, detail="gspread 라이브러리가 설치되어 있지 않습니다.")
try: try:
client = gspread.authorize(_load_credentials([SHEETS_SCOPE])) client = create_google_client(_load_credentials([SHEETS_SCOPE]))
spreadsheet = client.open_by_key(file_id) spreadsheet = client.open_by_key(file_id)
return { return {
"source": "google_sheet", "source": "google_sheet",
@@ -672,7 +673,8 @@ def _read_milkrun_sheet(content, sheet_name):
@router.post("/sheet-rows") @router.post("/sheet-rows")
async def get_sheet_rows(payload: SheetRowsRequest): @google_worker
def get_sheet_rows(payload: SheetRowsRequest):
"""선택한 시트의 제품코드/제품명/수량을 읽어 분석용 텍스트로 돌려준다.""" """선택한 시트의 제품코드/제품명/수량을 읽어 분석용 텍스트로 돌려준다."""
file_id = extract_file_id(payload.url or MILKRUN_SHEET_URL) file_id = extract_file_id(payload.url or MILKRUN_SHEET_URL)
if not payload.sheet: if not payload.sheet:
@@ -687,7 +689,8 @@ async def get_sheet_rows(payload: SheetRowsRequest):
@router.post("/sheet-tabs") @router.post("/sheet-tabs")
async def get_sheet_tabs(payload: SheetTabsRequest): @google_worker
def get_sheet_tabs(payload: SheetTabsRequest):
"""구글 드라이브 파일의 시트(탭) 이름 목록을 돌려준다.""" """구글 드라이브 파일의 시트(탭) 이름 목록을 돌려준다."""
file_id = extract_file_id(payload.url or MILKRUN_SHEET_URL) file_id = extract_file_id(payload.url or MILKRUN_SHEET_URL)
File diff suppressed because it is too large Load Diff
+24 -7
View File
@@ -114,14 +114,24 @@ async def create_return_request(req: ReturnRequest):
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@router.get("/request") @router.get("/request")
async def get_return_requests(tracking_no: Optional[str] = None): async def get_return_requests(tracking_no: Optional[str] = None, all_records: bool = False):
try: try:
conn = get_return_db_conn() conn = get_return_db_conn()
cur = conn.cursor() cur = conn.cursor()
if tracking_no: conditions, params = [], []
cur.execute("SELECT * FROM return_requests WHERE TRIM(tracking_no) = %s ORDER BY created_at DESC LIMIT 1", (tracking_no.strip(),)) if tracking_no and tracking_no.strip():
else: conditions.append("regexp_replace(r.tracking_no, '[-[:space:]]', '', 'g') = %s")
cur.execute("SELECT * FROM return_requests ORDER BY id DESC LIMIT 50") params.append(''.join(tracking_no.replace('-', '').split()))
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() rows = cur.fetchall()
conn.close() conn.close()
return {"success": True, "data": [dict(r) for r in rows]} return {"success": True, "data": [dict(r) for r in rows]}
@@ -271,11 +281,18 @@ async def create_return_receive(req: ReturnReceive):
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@router.get("/receive") @router.get("/receive")
async def get_return_receives(): async def get_return_receives(tracking_no: Optional[str] = None, all_records: bool = False):
try: try:
conn = get_return_db_conn() conn = get_return_db_conn()
cur = conn.cursor() cur = conn.cursor()
cur.execute("SELECT * FROM return_receivings ORDER BY receive_date DESC, mall ASC, id DESC LIMIT 50") conditions, params = [], []
if tracking_no and tracking_no.strip():
conditions.append("regexp_replace(tracking_no, '[-[:space:]]', '', 'g') = %s")
params.append(''.join(tracking_no.replace('-', '').split()))
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() rows = cur.fetchall()
conn.close() conn.close()
return {"success": True, "data": [dict(r) for r in rows]} return {"success": True, "data": [dict(r) for r in rows]}
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
.return-history-search { flex: 1 1 250px; min-width: 0; margin-left: auto; }
.return-history-search > label { display: block; font-size: .8rem; font-weight: 600; margin-bottom: 3px; }
.return-history-controls { display: flex; align-items: center; gap: 5px; }
.return-history-controls input { flex: 1; min-width: 0; width: 100%; height: 28px; padding: 3px 7px; border: 1px solid #94a3b8; border-radius: 4px; font-size: .8rem; box-sizing: border-box; }
.return-history-controls button { flex: 0 0 auto; height: 28px; padding: 0 9px; border: 0; border-radius: 4px; background: #334155; color: white; font-size: .78rem; cursor: pointer; }
.return-history-controls .return-history-reset { background: #e2e8f0; color: #334155; }
.return-history-search > [role="status"] { display: block; min-height: 16px; margin-top: 3px; font-size: .7rem; color: #475569; }
.return-history-heading { display: flex; align-items: center; gap: 12px; }
.return-history-heading label { display: inline-flex; align-items: center; gap: 4px; margin: 0; font-weight: normal; cursor: pointer; }
+82 -13
View File
@@ -1759,6 +1759,11 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}); });
} }
if (data.cs_record_warning) {
alert(data.cs_record_warning);
} else if (data.cs_record_saved_count > 0) {
showToast('CS 기록에 발주 내용을 한 건으로 자동 저장했습니다.');
}
document.getElementById('btn-reset').click(); document.getElementById('btn-reset').click();
if (url.includes('submit')) { if (url.includes('submit')) {
const iframe = document.querySelector('#manual-tab iframe'); const iframe = document.querySelector('#manual-tab iframe');
@@ -2834,27 +2839,45 @@ document.addEventListener('DOMContentLoaded', () => {
} }
// Load Lists // Load Lists
const returnHistoryQueries = { req: '', rec: '' };
const returnHistoryVersions = { req: 0, rec: 0 };
function returnHistoryUrl(kind, endpoint) {
const params = new URLSearchParams();
if (returnHistoryQueries[kind]) params.set('tracking_no', returnHistoryQueries[kind]);
if (document.getElementById(`${kind}-history-all`)?.checked) params.set('all_records', 'true');
return `/api/return/${endpoint}?${params}`;
}
function returnHistoryStatus(kind, count, error = '') {
const status = document.getElementById(`${kind}-history-status`);
if (!status) return;
const scope = returnHistoryQueries[kind] ? '전체 기록 검색' :
(document.getElementById(`${kind}-history-all`)?.checked ? '전체 기록' : '최근 3개월');
status.textContent = error || `${scope} · ${count}건`;
}
async function loadReturnRequests() { async function loadReturnRequests() {
const tbody = document.getElementById('tbody-return-requests'); const tbody = document.getElementById('tbody-return-requests');
if(!tbody) return; if(!tbody) return;
const version = ++returnHistoryVersions.req;
try { try {
const res = await fetch('/api/return/request'); const res = await fetch(returnHistoryUrl('req', 'request'));
const recRes = await fetch('/api/return/receive'); if (!res.ok) throw new Error('신청 목록을 불러오지 못했습니다.');
if(res.ok && recRes.ok) { if(res.ok) {
const data = await res.json(); const data = await res.json();
const recData = await recRes.json(); if (version !== returnHistoryVersions.req) return;
const receivedTrackingNos = new Set((recData.data || []).map(r => r.tracking_no).filter(t => t)); if (!data.success) throw new Error('신청 목록을 불러오지 못했습니다.');
tbody.innerHTML = ''; tbody.innerHTML = '';
if(data.data) { if(data.data) {
const excludeReceived = document.getElementById('chk-exclude-received')?.checked; const excludeReceived = document.getElementById('chk-exclude-received')?.checked;
let displayData = data.data; let displayData = data.data;
if (excludeReceived) { if (excludeReceived && !returnHistoryQueries.req) {
displayData = displayData.filter(i => !(i.tracking_no && receivedTrackingNos.has(i.tracking_no))); displayData = displayData.filter(i => !i.is_received);
} }
returnHistoryStatus('req', displayData.length);
if (!displayData.length) tbody.innerHTML = '<tr><td colspan="8" style="padding:20px;text-align:center">해당하는 신청 내역이 없습니다.</td></tr>';
displayData.forEach(item => { displayData.forEach(item => {
const isReceived = item.tracking_no && receivedTrackingNos.has(item.tracking_no); const isReceived = item.is_received;
const tr = document.createElement('tr'); const tr = document.createElement('tr');
tr.style.cursor = 'pointer'; tr.style.cursor = 'pointer';
let displayRemarks = item.remarks || ''; let displayRemarks = item.remarks || '';
@@ -2922,24 +2945,35 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
} }
} }
} catch(e) {} } catch(e) {
if (version === returnHistoryVersions.req) {
tbody.replaceChildren();
returnHistoryStatus('req', 0, e.message);
}
}
} }
async function loadReturnReceivings() { async function loadReturnReceivings() {
const tbody = document.getElementById('tbody-return-receivings'); const tbody = document.getElementById('tbody-return-receivings');
if(!tbody) return; if(!tbody) return;
const version = ++returnHistoryVersions.rec;
try { try {
const res = await fetch('/api/return/receive'); const res = await fetch(returnHistoryUrl('rec', 'receive'));
if (!res.ok) throw new Error('입고 목록을 불러오지 못했습니다.');
if(res.ok) { if(res.ok) {
const data = await res.json(); const data = await res.json();
if (version !== returnHistoryVersions.rec) return;
if (!data.success) throw new Error('입고 목록을 불러오지 못했습니다.');
tbody.innerHTML = ''; tbody.innerHTML = '';
if(data.data) { if(data.data) {
const excludeCompleted = document.getElementById('chk-exclude-completed')?.checked; const excludeCompleted = document.getElementById('chk-exclude-completed')?.checked;
let displayData = data.data; let displayData = data.data;
if (excludeCompleted) { if (excludeCompleted && !returnHistoryQueries.rec) {
displayData = displayData.filter(i => i.receive_status !== '환불완료' && i.receive_status !== '교환완료'); displayData = displayData.filter(i => i.receive_status !== '환불완료' && i.receive_status !== '교환완료');
} }
returnHistoryStatus('rec', displayData.length);
if (!displayData.length) tbody.innerHTML = '<tr><td colspan="8" style="padding:20px;text-align:center">해당하는 입고 내역이 없습니다.</td></tr>';
displayData.forEach(item => { displayData.forEach(item => {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
tr.style.cursor = 'pointer'; tr.style.cursor = 'pointer';
@@ -2993,10 +3027,45 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
} }
} }
} catch(e) {} } catch(e) {
if (version === returnHistoryVersions.rec) {
tbody.replaceChildren();
returnHistoryStatus('rec', 0, e.message);
}
}
} }
// Initial load // Initial load
for (const [kind, reload, excludeId] of [
['req', loadReturnRequests, 'chk-exclude-received'],
['rec', loadReturnReceivings, 'chk-exclude-completed']
]) {
const input = document.getElementById(`${kind}-history-tracking`);
const all = document.getElementById(`${kind}-history-all`);
const search = () => {
const query = input.value.replace(/[-\s]/g, '');
if (!query) { returnHistoryStatus(kind, 0, '원송장번호를 입력해주세요.'); input.focus(); return; }
returnHistoryQueries[kind] = query;
document.getElementById(excludeId).checked = false;
reload();
};
document.getElementById(`${kind}-history-search`)?.addEventListener('click', search);
input?.addEventListener('keydown', event => {
if (event.key === 'Enter') { event.preventDefault(); search(); }
});
document.getElementById(`${kind}-history-reset`)?.addEventListener('click', () => {
input.value = '';
returnHistoryQueries[kind] = '';
all.checked = false;
document.getElementById(excludeId).checked = false;
reload();
});
all?.addEventListener('change', () => {
input.value = '';
returnHistoryQueries[kind] = '';
reload();
});
}
const returnTabMenu = document.querySelector('[data-tab="return-tab"]'); const returnTabMenu = document.querySelector('[data-tab="return-tab"]');
const chkExcludeCompleted = document.getElementById('chk-exclude-completed'); const chkExcludeCompleted = document.getElementById('chk-exclude-completed');
@@ -4188,7 +4257,7 @@ if (recFormContainer) {
// Version Update Notice // Version Update Notice
// ============================================ // ============================================
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
let CURRENT_APP_VERSION = "9.0"; let CURRENT_APP_VERSION = "9.1";
const versionEl = document.getElementById('app-version-text'); const versionEl = document.getElementById('app-version-text');
if (versionEl) { if (versionEl) {
const text = versionEl.textContent.trim(); const text = versionEl.textContent.trim();
File diff suppressed because it is too large Load Diff
+6 -5
View File
@@ -1,7 +1,8 @@
// 쿠팡 밀크런 캘린더 // 쿠팡 밀크런 캘린더
// //
// 화면이 열리면 구글 드라이브의 밀크런 출고리스트를 자동으로 읽어 // 밀크런 탭을 열었을 때만 구글 드라이브의 밀크런 출고리스트를 읽어
// 시트 이름(YYYYMMDD)을 달력에 표시한다. // 시트 이름(YYYYMMDD)을 달력에 표시한다. 메인 화면 로딩 중에는
// 구글 시트 조회나 분석 요청을 실행하지 않는다.
// 달력에서 날짜를 고르면 그 시트의 제품코드/제품명/수량을 읽어 // 달력에서 날짜를 고르면 그 시트의 제품코드/제품명/수량을 읽어
// 붙여넣기 입력을 채우고 곧바로 분석까지 실행한다. // 붙여넣기 입력을 채우고 곧바로 분석까지 실행한다.
// (시트 주소는 서버에 설정되어 있어 화면에서 입력하지 않는다) // (시트 주소는 서버에 설정되어 있어 화면에서 입력하지 않는다)
@@ -356,8 +357,8 @@
}); });
} }
// 달력 틀을 먼저 보여주고(덮개가 '읽는 중'을 표시), 출고일은 뒤이어 채운다 // 초기 화면에서는 달력 틀만 준비한다. 실제 조회와 분석은 위의
renderCalendar(); // 밀크런 메뉴 클릭 이벤트에서만 시작한다.
loadSheetTabs(false); renderCalendar('밀크런 탭을 열면 출고일을 불러옵니다');
}); });
})(); })();
+276 -6
View File
@@ -15,6 +15,8 @@
rel="stylesheet" rel="stylesheet"
href="{{ root_path }}/static/css/styles.css?v=24" href="{{ root_path }}/static/css/styles.css?v=24"
/> />
<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" />
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script> <script>
// 서브경로 호스팅 정보 — JS 가 fetch 시 prefix 로 사용한다. // 서브경로 호스팅 정보 — JS 가 fetch 시 prefix 로 사용한다.
@@ -95,10 +97,10 @@
id="app-version-text" id="app-version-text"
style="color: #a0aec0; font-size: 0.95rem; margin-top: 4px; font-weight: normal" style="color: #a0aec0; font-size: 0.95rem; margin-top: 4px; font-weight: normal"
> >
Ver 9.0 Ver 9.1
</div> </div>
<div style="color: #a0aec0; font-size: 0.75rem; margin-top: 4px; font-weight: normal"> <div style="color: #a0aec0; font-size: 0.75rem; margin-top: 4px; font-weight: normal">
(2026.08.25) (2026.09.03)
</div> </div>
</div> </div>
<ul class="nav-links"> <ul class="nav-links">
@@ -109,6 +111,7 @@
<span class="nav-icon">🎧</span>CS 작업 <span class="nav-icon">🎧</span>CS 작업
</li> </li>
<li class="active" data-tab="order-tab" data-order-view="new"><span class="nav-icon">✨</span>New CS</li> <li class="active" data-tab="order-tab" data-order-view="new"><span class="nav-icon">✨</span>New CS</li>
<li data-tab="cs-record-tab"><span class="nav-icon">📝</span>CS 기록</li>
<li data-tab="manual-tab"><span class="nav-icon">✍️</span>수동발주</li> <li data-tab="manual-tab"><span class="nav-icon">✍️</span>수동발주</li>
<li data-tab="product-tab"><span class="nav-icon">📦</span>상품설정</li> <li data-tab="product-tab"><span class="nav-icon">📦</span>상품설정</li>
<li data-tab="auto-order-tab"><span class="nav-icon">🤖</span>자동발주</li> <li data-tab="auto-order-tab"><span class="nav-icon">🤖</span>자동발주</li>
@@ -571,6 +574,254 @@
</div> </div>
</div> </div>
</section> </section>
<!-- =========================
CS RECORD TAB
========================== -->
<section id="cs-record-tab" class="tab-content cs-record-tab">
<div class="cs-record-layout">
<aside class="cs-calendar-card">
<div class="cs-calendar-header">
<button id="cs-calendar-prev" type="button" class="cs-icon-button" aria-label="이전 달">‹</button>
<h2 id="cs-calendar-title">-</h2>
<button id="cs-calendar-next" type="button" class="cs-icon-button" aria-label="다음 달">›</button>
</div>
<div class="cs-calendar-weekdays" aria-hidden="true">
<span>일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span>토</span>
</div>
<div id="cs-calendar-grid" class="cs-calendar-grid" aria-label="CS 기록 달력"></div>
<div class="cs-calendar-legend">
<span><i class="cs-legend-dot has-record"></i>기록 있음</span>
<span><i class="cs-legend-dot incomplete"></i>미완료 있음</span>
<span><i class="cs-legend-dot schedule"></i>일정 있음</span>
</div>
<section class="cs-schedule-panel" aria-labelledby="cs-schedule-list-title">
<div class="cs-schedule-primary-actions">
<button id="cs-open-schedule-modal" type="button" class="cs-schedule-add-button">+일정 등록</button>
<button id="cs-open-data-modal" type="button" class="cs-schedule-settings-button" aria-label="일정 데이터 설정" title="엑셀 내려받기·데이터 업로드">⚙️</button>
</div>
<div class="cs-schedule-list-header">
<h3 id="cs-schedule-list-title">이번 달 일정</h3>
<span id="cs-schedule-count">0개</span>
</div>
<div id="cs-schedule-list" class="cs-schedule-list"></div>
</section>
</aside>
<div class="cs-record-card">
<header class="cs-record-header">
<div>
<span class="cs-eyebrow">일별 상담·전달 기록</span>
<h1 id="cs-selected-date-title">-</h1>
<p id="cs-record-count">기록을 불러오는 중입니다.</p>
</div>
<div class="cs-record-actions">
<button id="cs-copy-selected" type="button" class="cs-copy-selected-button">체크내용 복사</button>
<button id="cs-copy-next" type="button" class="cs-copy-button">다음 업무일로 미완료 복사</button>
</div>
</header>
<div id="cs-record-status" class="cs-record-status" role="status" hidden></div>
<div class="cs-record-composer">
<textarea id="cs-record-input" rows="3" maxlength="10000" placeholder="고객 상담 내용이나 물류센터 전달 사항을 입력하세요."></textarea>
<div class="cs-composer-footer">
<span>Ctrl + Enter로 빠르게 추가</span>
<button id="cs-record-add" type="button" class="cs-primary-button">기록 추가</button>
</div>
</div>
<div id="cs-record-list" class="cs-record-list"></div>
</div>
<aside class="cs-permanent-card">
<header class="cs-permanent-header">
<div>
<span class="cs-eyebrow">날짜와 관계없이 항상 표시</span>
<h2>📌 항상 확인 메모</h2>
</div>
<button id="cs-open-memo-modal" type="button" class="cs-add-memo-button">+ 메모 추가</button>
</header>
<div class="cs-folder-toolbar">
<div id="cs-folder-tabs" class="cs-folder-tabs" role="tablist" aria-label="메모 폴더"></div>
<div class="cs-folder-actions">
<button id="cs-open-folder-add" type="button">폴더 추가</button>
<button id="cs-open-folder-delete" type="button">폴더 삭제</button>
</div>
</div>
<div id="cs-permanent-list" class="cs-permanent-list"></div>
</aside>
</div>
<div id="cs-schedule-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-schedule-modal-title">
<div class="cs-schedule-modal-heading">
<span class="cs-schedule-modal-icon" aria-hidden="true">📅</span>
<div>
<span class="cs-eyebrow">CS 캘린더</span>
<h3 id="cs-schedule-modal-title">일정 등록</h3>
</div>
</div>
<div class="cs-schedule-form-row cs-schedule-date-row">
<div>
<label for="cs-schedule-date">시작일</label>
<input id="cs-schedule-date" type="date" required />
</div>
<div>
<label for="cs-schedule-end-date">종료일</label>
<input id="cs-schedule-end-date" type="date" required />
</div>
<label class="cs-all-day-toggle" for="cs-schedule-all-day">
<input id="cs-schedule-all-day" type="checkbox" />
<span aria-hidden="true"></span>
종일
</label>
</div>
<div class="cs-schedule-form-row cs-schedule-time-row">
<div>
<label for="cs-schedule-time">시작 시간 <span class="cs-optional-label">선택</span></label>
<div id="cs-schedule-time" class="cs-time-select-group" aria-label="시작 시간">
<select id="cs-schedule-start-period" aria-label="시작 시간 오전 오후">
<option value="">선택</option><option value="AM">오전</option><option value="PM">오후</option>
</select>
<select id="cs-schedule-start-hour" aria-label="시작 시">
<option value="">시</option><option value="01">01</option><option value="02">02</option><option value="03">03</option><option value="04">04</option><option value="05">05</option><option value="06">06</option><option value="07">07</option><option value="08">08</option><option value="09">09</option><option value="10">10</option><option value="11">11</option><option value="12">12</option>
</select>
<select id="cs-schedule-start-minute" aria-label="시작 분">
<option value="">분</option><option value="00">00</option><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option>
</select>
</div>
</div>
<div>
<label for="cs-schedule-end-time">종료 시간 <span class="cs-optional-label">선택</span></label>
<div id="cs-schedule-end-time" class="cs-time-select-group" aria-label="종료 시간">
<select id="cs-schedule-end-period" aria-label="종료 시간 오전 오후">
<option value="">선택</option><option value="AM">오전</option><option value="PM">오후</option>
</select>
<select id="cs-schedule-end-hour" aria-label="종료 시">
<option value="">시</option><option value="01">01</option><option value="02">02</option><option value="03">03</option><option value="04">04</option><option value="05">05</option><option value="06">06</option><option value="07">07</option><option value="08">08</option><option value="09">09</option><option value="10">10</option><option value="11">11</option><option value="12">12</option>
</select>
<select id="cs-schedule-end-minute" aria-label="종료 분">
<option value="">분</option><option value="00">00</option><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option>
</select>
</div>
</div>
</div>
<label for="cs-schedule-title">일정 내용</label>
<input id="cs-schedule-title" type="text" maxlength="300" placeholder="예: 물류센터 재고 확인" />
<p class="cs-modal-help">시작일과 종료일을 다르게 선택하면 기간 일정이 됩니다. 종일을 체크하면 시간 없이 저장됩니다.</p>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-schedule-modal">취소</button>
<button id="cs-schedule-save" type="button" class="cs-modal-save">일정 저장</button>
</div>
</div>
</div>
<div id="cs-schedule-delete-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-schedule-delete-title">
<h3 id="cs-schedule-delete-title">일정 삭제</h3>
<p class="cs-delete-message">이 일정을 삭제할까요?</p>
<div id="cs-schedule-delete-preview" class="cs-schedule-delete-preview"></div>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-schedule-delete-modal">취소</button>
<button id="cs-schedule-delete-save" type="button" class="cs-modal-delete">일정 삭제</button>
</div>
</div>
</div>
<div id="cs-data-modal" class="cs-modal cs-data-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-data-modal-title">
<div class="cs-schedule-modal-heading">
<span class="cs-schedule-modal-icon" aria-hidden="true">⚙️</span>
<div>
<span class="cs-eyebrow">CS 캘린더</span>
<h3 id="cs-data-modal-title">데이터 관리</h3>
</div>
</div>
<p class="cs-data-modal-description">CS 기록, 상시 메모와 일정을 엑셀로 백업하거나 이전에 내려받은 파일을 다시 업로드할 수 있습니다.</p>
<div class="cs-data-actions">
<a id="cs-record-export" class="cs-secondary-button" href="{{ root_path }}/api/cs-records/export">엑셀 내려받기</a>
<label class="cs-secondary-button" for="cs-record-import">데이터 업로드</label>
<input id="cs-record-import" type="file" accept=".xlsx,.xls,.csv" hidden />
</div>
<p class="cs-upload-help">내려받은 엑셀 또는 날짜·내용 열이 있는 파일을 업로드할 수 있습니다.</p>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-save" data-cs-close="cs-data-modal">닫기</button>
</div>
</div>
</div>
<div id="cs-memo-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="cs-memo-modal-title">
<h3 id="cs-memo-modal-title">메모 추가</h3>
<label for="cs-memo-folder-select">메모 폴더</label>
<select id="cs-memo-folder-select"></select>
<label for="cs-memo-content">메모 내용</label>
<textarea id="cs-memo-content" rows="7" maxlength="10000" placeholder="항상 확인할 메모 내용을 입력하세요."></textarea>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-memo-modal">취소</button>
<button id="cs-memo-save" type="button" class="cs-modal-save">저장</button>
</div>
</div>
</div>
<div id="cs-folder-add-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-folder-add-title">
<h3 id="cs-folder-add-title">메모 폴더 추가</h3>
<label for="cs-folder-name">추가할 폴더 이름</label>
<input id="cs-folder-name" type="text" maxlength="80" placeholder="예: 물류센터 전달" />
<fieldset class="cs-color-fieldset">
<legend>폴더 색상</legend>
<div id="cs-folder-add-colors" class="cs-color-palette" aria-label="폴더 색상 선택"></div>
</fieldset>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-folder-add-modal">취소</button>
<button id="cs-folder-add-save" type="button" class="cs-modal-save">폴더 추가</button>
</div>
</div>
</div>
<div id="cs-folder-edit-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-folder-edit-title">
<h3 id="cs-folder-edit-title">메모 폴더 설정</h3>
<label for="cs-folder-edit-name">폴더 이름</label>
<input id="cs-folder-edit-name" type="text" maxlength="80" />
<fieldset class="cs-color-fieldset">
<legend>폴더 색상</legend>
<div id="cs-folder-edit-colors" class="cs-color-palette" aria-label="폴더 색상 선택"></div>
</fieldset>
<p class="cs-modal-help">폴더 탭을 더블클릭하면 언제든지 설정을 변경할 수 있습니다.</p>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-folder-edit-modal">취소</button>
<button id="cs-folder-edit-save" type="button" class="cs-modal-save">설정 저장</button>
</div>
</div>
</div>
<div id="cs-folder-delete-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-folder-delete-title">
<h3 id="cs-folder-delete-title">메모 폴더 삭제</h3>
<label for="cs-folder-delete-select">삭제할 폴더</label>
<select id="cs-folder-delete-select"></select>
<p class="cs-modal-help">폴더 안의 메모는 삭제되지 않고 기본 폴더로 이동합니다.</p>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-folder-delete-modal">취소</button>
<button id="cs-folder-delete-save" type="button" class="cs-modal-delete">폴더 삭제</button>
</div>
</div>
</div>
<div id="cs-memo-delete-modal" class="cs-modal" hidden>
<div class="cs-modal-dialog cs-modal-dialog-small" role="dialog" aria-modal="true" aria-labelledby="cs-memo-delete-title">
<h3 id="cs-memo-delete-title">상시 메모 삭제</h3>
<p class="cs-delete-message">이 상시 메모를 삭제할까요?</p>
<div id="cs-memo-delete-preview" class="cs-memo-delete-preview"></div>
<div class="cs-modal-actions">
<button type="button" class="cs-modal-cancel" data-cs-close="cs-memo-delete-modal">취소</button>
<button id="cs-memo-delete-save" type="button" class="cs-modal-delete">메모 삭제</button>
</div>
</div>
</div>
</section>
<!-- ========================= <!-- =========================
AUTO ORDER TAB AUTO ORDER TAB
========================== --> ========================== -->
@@ -3054,6 +3305,15 @@
<option value="기타">기타</option> <option value="기타">기타</option>
</select> </select>
</div> </div>
<div class="return-history-search">
<label for="req-history-tracking">원송장번호 검색 (전체 신청 내역)</label>
<div class="return-history-controls">
<input id="req-history-tracking" type="search" placeholder="원송장번호 입력" autocomplete="off" />
<button id="req-history-search" type="button">검색</button>
<button id="req-history-reset" type="button" class="return-history-reset">초기화</button>
</div>
<span id="req-history-status" role="status">최근 3개월</span>
</div>
</div> </div>
<div <div
class="mobile-hide" class="mobile-hide"
@@ -3157,7 +3417,7 @@
align-items: center; align-items: center;
" "
> >
<span>신청 목록</span <span class="return-history-heading">신청 목록 <label><input id="req-history-all" type="checkbox" /> 전체 보기</label></span
><label ><label
style=" style="
cursor: pointer; cursor: pointer;
@@ -3430,6 +3690,15 @@
<option value="교환완료">교환완료</option> <option value="교환완료">교환완료</option>
</select> </select>
</div> </div>
<div class="return-history-search">
<label for="rec-history-tracking">원송장번호 검색 (전체 입고 내역)</label>
<div class="return-history-controls">
<input id="rec-history-tracking" type="search" placeholder="원송장번호 입력" autocomplete="off" />
<button id="rec-history-search" type="button">검색</button>
<button id="rec-history-reset" type="button" class="return-history-reset">초기화</button>
</div>
<span id="rec-history-status" role="status">최근 3개월</span>
</div>
</div> </div>
<!-- Line 2 --> <!-- Line 2 -->
<div <div
@@ -3637,7 +3906,7 @@
align-items: center; align-items: center;
" "
> >
<span>입고 목록</span <span class="return-history-heading">입고 목록 <label><input id="rec-history-all" type="checkbox" /> 전체 보기</label></span
><label ><label
style=" style="
cursor: pointer; cursor: pointer;
@@ -3737,9 +4006,10 @@
{% include 'version_history.html' %} {% include 'version_history.html' %}
</main> </main>
</div> </div>
<script src="{{ root_path }}/static/js/app.js?v=69"></script> <script src="{{ root_path }}/static/js/app.js?v=72"></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> <script src="{{ root_path }}/static/js/mall_event.js?v=7"></script>
<script src="{{ root_path }}/static/js/milkrun_gsheet.js?v=7"></script> <script src="{{ root_path }}/static/js/milkrun_gsheet.js?v=8"></script>
<!-- Toast Notification --> <!-- Toast Notification -->
<div <div
+293
View File
@@ -0,0 +1,293 @@
"""Fault-injection tests. All Google writes and DB connections are replaced."""
import asyncio
import copy
import json
import os
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from urllib.parse import urlsplit
import requests
_import_cache_dir = tempfile.TemporaryDirectory()
os.environ["SETTINGS_CACHE_FILE"] = str(Path(_import_cache_dir.name) / "settings.json")
# 서버판(dbx-corm)은 SSO 미들웨어가 세션 비밀값을 요구하고, 로그인 안 된 요청을 401 로 막는다.
# 테스트는 서비스 간 호출 토큰(X-Service-Token)으로 통과한다.
os.environ.setdefault("SESSION_SECRET_KEY", "test-only-session-secret")
os.environ["INTERNAL_SERVICE_TOKEN"] = "test-service-token"
import main
import google_runtime as runtime
import routers.cs_records as records
ROWS = [["대분류 (Section)", "항목 (Key)", "설정값 1"], ["APP_SETTINGS", "theme", "old"]]
async def request(method, url, payload=None):
parsed = urlsplit(url)
body = b"" if payload is None else json.dumps(payload).encode()
events = []
received = False
async def receive():
nonlocal received
if not received:
received = True
return {"type": "http.request", "body": body, "more_body": False}
await asyncio.Event().wait()
async def send(event):
events.append(event)
await main.app({
"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
"method": method, "scheme": "http", "path": parsed.path,
"raw_path": parsed.path.encode(), "query_string": parsed.query.encode(),
"root_path": "", "server": ("test", 80), "client": ("127.0.0.1", 1234),
"headers": [(b"content-type", b"application/json"), (b"x-service-token", b"test-service-token")],
}, receive, send)
start = next(e for e in events if e["type"] == "http.response.start")
content = b"".join(e.get("body", b"") for e in events if e["type"] == "http.response.body")
return start["status"], dict(start["headers"]), content
async def wait_until(predicate):
async with asyncio.timeout(2):
while not predicate():
await asyncio.sleep(0.005)
class CacheTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.cache = runtime.SettingsCache(Path(self.directory.name) / "settings.json", "test", ttl=60)
def tearDown(self):
self.cache.close()
self.directory.cleanup()
def test_fresh_cache_and_callers_cannot_mutate_snapshot(self):
loader = MagicMock(return_value=copy.deepcopy(ROWS))
first = self.cache.read(loader)
first[1][2] = "changed outside cache"
self.assertEqual(self.cache.read(loader), ROWS)
loader.assert_called_once()
def test_stale_reads_are_immediate_and_refresh_is_single_flight(self):
self.cache.publish(ROWS)
self.cache.invalidate()
started, release = threading.Event(), threading.Event()
def slow_load():
started.set()
release.wait(2)
return [["new"]]
loader = MagicMock(side_effect=slow_load)
try:
began = time.monotonic()
self.assertEqual(self.cache.read(loader), ROWS)
self.assertLess(time.monotonic() - began, 0.2)
self.assertTrue(started.wait(1))
for _ in range(20):
self.assertEqual(self.cache.read(loader), ROWS)
self.assertEqual(loader.call_count, 1)
finally:
release.set()
self.cache._pending.result(2)
self.assertEqual(self.cache.read(loader), [["new"]])
def test_restart_restores_snapshot_when_google_is_down(self):
self.cache.publish(ROWS)
restored = runtime.SettingsCache(self.cache.path, "test")
try:
loader = MagicMock(side_effect=requests.ReadTimeout())
self.assertEqual(restored.read(loader), ROWS)
restored._pending.result(2)
for _ in range(10):
self.assertEqual(restored.read(loader), ROWS)
self.assertEqual(loader.call_count, 1)
finally:
restored.close()
def test_background_read_cannot_replace_a_later_save(self):
self.cache.publish(ROWS)
self.cache.invalidate()
started, release = threading.Event(), threading.Event()
def slow_load():
started.set()
release.wait(2)
return ROWS
try:
self.cache.read(slow_load)
self.assertTrue(started.wait(1))
self.cache.publish([["saved later"]])
finally:
release.set()
self.cache._pending.result(2)
self.assertEqual(self.cache.read(slow_load), [["saved later"]])
self.assertEqual(json.loads(self.cache.path.read_text(encoding="utf-8"))["rows"], [["saved later"]])
def test_force_refresh_failure_is_not_hidden_by_cache(self):
self.cache.publish(ROWS)
with self.assertRaises(requests.ReadTimeout):
self.cache.read(MagicMock(side_effect=requests.ReadTimeout()), force=True)
self.assertEqual(self.cache.read(MagicMock()), ROWS)
def test_cache_cannot_be_reused_for_a_different_spreadsheet(self):
self.cache.publish(ROWS)
other = runtime.SettingsCache(self.cache.path, "different-sheet")
try:
self.assertFalse(other.has_value)
finally:
other.close()
class TimeoutTests(unittest.TestCase):
def test_auth_refresh_default_timeout_is_capped(self):
with patch.object(requests.Session, "request", return_value=object()) as send:
runtime.GoogleTimeoutSession().request("POST", "https://example.invalid", timeout=120)
self.assertEqual(send.call_args.kwargs["timeout"], runtime.GOOGLE_TIMEOUT)
def test_authorized_requests_are_bounded_even_with_no_timeout(self):
session = runtime.create_google_session(MagicMock())
with patch.object(runtime.AuthorizedSession, "request", return_value=object()) as send:
session.request("GET", "https://example.invalid", timeout=None)
self.assertEqual(send.call_args.kwargs["timeout"], runtime.GOOGLE_TIMEOUT)
class ApiTests(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.cache = runtime.SettingsCache(Path(self.directory.name) / "settings.json", "test")
self.cache_patch = patch.object(main, "_settings_cache", self.cache)
self.cache_patch.start()
def tearDown(self):
self.cache_patch.stop()
self.cache.close()
self.directory.cleanup()
async def test_google_hang_does_not_block_page_or_db_records(self):
started, release = threading.Event(), threading.Event()
def stalled_google():
started.set()
release.wait(3)
raise requests.ReadTimeout()
connection = MagicMock()
connection.cursor.return_value.__enter__.return_value.fetchall.return_value = []
with patch.object(main, "_load_settings_rows", stalled_google), \
patch.object(records, "_ensure_schema"), patch.object(records, "_connect", return_value=connection):
config_task = asyncio.create_task(request("GET", "/api/config"))
try:
await wait_until(started.is_set)
async with asyncio.timeout(1):
page = await request("GET", "/")
db = await request("GET", "/api/cs-records?record_date=2026-10-19")
self.assertEqual(page[0], 200)
self.assertEqual(db[0], 200)
self.assertEqual(json.loads(db[2])["records"], [])
self.assertFalse(config_task.done())
finally:
release.set()
response = await config_task
self.assertEqual(response[0], 503)
async def test_saturation_keeps_db_pool_and_cached_settings_available(self):
release = threading.Event()
started = []
def stalled():
started.append(True)
release.wait(3)
self.cache.publish(ROWS)
tasks = [asyncio.create_task(runtime.run_google_io(stalled)) for _ in range(runtime.GOOGLE_WORKERS)]
try:
await wait_until(lambda: len(started) == runtime.GOOGLE_WORKERS)
with self.assertRaises(main.HTTPException) as error:
await runtime.run_google_io(lambda: None)
self.assertEqual(error.exception.status_code, 503)
async with asyncio.timeout(1):
config = await request("GET", "/api/config")
page = await request("GET", "/")
self.assertEqual(config[0], 200)
self.assertEqual(page[0], 200)
finally:
release.set()
await asyncio.gather(*tasks)
async def test_settings_save_uses_one_atomic_write_and_updates_cache(self):
self.cache.publish(ROWS)
worksheet = MagicMock(id=123, row_count=999, col_count=26)
worksheet.get_all_values.return_value = copy.deepcopy(ROWS)
with patch.object(main, "get_settings_worksheet", return_value=worksheet):
saved = await request("POST", "/api/app/settings", {"theme": "new"})
self.assertEqual(saved[0], 200)
worksheet.clear.assert_not_called()
worksheet.update.assert_not_called()
worksheet.spreadsheet.batch_update.assert_called_once()
body = worksheet.spreadsheet.batch_update.call_args.args[0]
change = body["requests"][-1]["updateCells"]
self.assertEqual(change["range"], {"sheetId": 123})
self.assertEqual(change["fields"], "userEnteredValue")
self.assertEqual(change["rows"][1]["values"][2]["userEnteredValue"]["stringValue"], "new")
response = await request("GET", "/api/config")
self.assertEqual(json.loads(response[2])["APP_SETTINGS"]["theme"], "new")
self.assertEqual(worksheet.get_all_values.call_count, 1)
async def test_save_does_not_use_stale_settings_during_outage(self):
self.cache.publish(ROWS)
worksheet = MagicMock()
worksheet.get_all_values.side_effect = requests.ReadTimeout()
with patch.object(main, "get_settings_worksheet", return_value=worksheet):
response = await request("POST", "/api/app/settings", {"theme": "new"})
self.assertEqual(response[0], 503)
worksheet.spreadsheet.batch_update.assert_not_called()
self.assertEqual(self.cache.read(MagicMock()), ROWS)
async def test_failed_write_never_publishes_unconfirmed_values(self):
self.cache.publish(ROWS)
worksheet = MagicMock(id=123, row_count=999, col_count=26)
worksheet.get_all_values.return_value = copy.deepcopy(ROWS)
worksheet.spreadsheet.batch_update.side_effect = requests.ReadTimeout()
with patch.object(main, "get_settings_worksheet", return_value=worksheet):
response = await request("POST", "/api/app/settings", {"theme": "new"})
self.assertEqual(response[0], 503)
self.assertEqual(self.cache._rows, ROWS)
self.assertTrue(self.cache.stale)
async def test_concurrent_settings_updates_preserve_both_changes(self):
remote_rows = copy.deepcopy(ROWS)
worksheet = MagicMock(id=123, row_count=999, col_count=26)
worksheet.get_all_values.side_effect = lambda: copy.deepcopy(remote_rows)
def atomic_save(body):
remote_rows[:] = [[c["userEnteredValue"]["stringValue"] for c in row["values"]]
for row in body["requests"][-1]["updateCells"]["rows"]]
worksheet.spreadsheet.batch_update.side_effect = atomic_save
with patch.object(main, "get_settings_worksheet", return_value=worksheet):
results = await asyncio.gather(
request("POST", "/api/app/settings", {"first": "1"}),
request("POST", "/api/app/settings", {"second": "2"}),
)
self.assertTrue(all(result[0] == 200 for result in results))
result = await request("GET", "/api/config")
settings = json.loads(result[2])["APP_SETTINGS"]
self.assertEqual(settings["first"], "1")
self.assertEqual(settings["second"], "2")
if __name__ == "__main__":
unittest.main()
+15
View File
@@ -1,4 +1,19 @@
[ [
{
"version": "v9.1",
"date": "2026.09.03",
"sections": [
{
"items": [
"CS 기록 메뉴 및 CS 메모 기능 추가: 달력 날짜별 고객 상담·물류센터 전달 내용 기록, 완료 처리, 선택 내용 복사, 다음 업무일 이월 기능 제공",
"항상 확인 메모 기능 추가: 폴더별 분류, 7가지 폴더 색상, 2열 포스트잇 화면, 메모·폴더 추가·수정·삭제 팝업 제공",
"CS 기록과 상시 메모를 PostgreSQL 서버에 저장하고 엑셀로 내려받기·업로드할 수 있도록 구성",
"New CS에서 누락·파손·불량·오배송 발주 입력 시 해당 내용을 CS 기록에 자동 저장"
],
"type": "added"
}
]
},
{ {
"version": "v9.0", "version": "v9.0",
"date": "2026.08.25", "date": "2026.08.25",