Merge branch 'feat/v9.1-merge'
This commit is contained in:
@@ -37,3 +37,6 @@ deploy.ps1
|
|||||||
start.bat
|
start.bat
|
||||||
test.ps1
|
test.ps1
|
||||||
*.xlsx
|
*.xlsx
|
||||||
|
|
||||||
|
# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache)
|
||||||
|
.cache/
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -44,3 +44,6 @@ deploy.bat
|
|||||||
deploy.ps1
|
deploy.ps1
|
||||||
start.bat
|
start.bat
|
||||||
test.ps1
|
test.ps1
|
||||||
|
|
||||||
|
# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache)
|
||||||
|
.cache/
|
||||||
|
|||||||
@@ -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`)
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -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 = []
|
try:
|
||||||
|
rows = _settings_cache.read(_load_settings_rows, force=force_refresh)
|
||||||
# 1. 캐시 유효성 판단 (force_refresh 가 아니고, 캐시가 존재하며, TTL 이 지나지 않은 경우)
|
except Exception as exc:
|
||||||
if not force_refresh and _CONFIG_ROWS_CACHE is not None:
|
raise HTTPException(
|
||||||
if time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL:
|
status_code=503,
|
||||||
rows = _CONFIG_ROWS_CACHE
|
detail="구글에서 최신 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.",
|
||||||
|
) from exc
|
||||||
# 2. 캐시가 없거나 만료된 경우 구글 시트에서 직접 새로 로드
|
|
||||||
if not rows:
|
|
||||||
with _CONFIG_LOCK:
|
|
||||||
# 락 대기 중 다른 스레드가 캐시를 갱신했을 수 있으므로 다시 검사 (Double-Checked Locking)
|
|
||||||
if not force_refresh and _CONFIG_ROWS_CACHE is not None and time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL:
|
|
||||||
rows = _CONFIG_ROWS_CACHE
|
|
||||||
else:
|
|
||||||
for _ in range(3):
|
|
||||||
try:
|
|
||||||
ws = get_settings_worksheet()
|
|
||||||
rows = ws.get_all_values()
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
time.sleep(1.5)
|
|
||||||
print(f"Google Sheets 불러오기 재시도 중...: {e}")
|
|
||||||
|
|
||||||
if rows:
|
|
||||||
_CONFIG_ROWS_CACHE = rows
|
|
||||||
_CONFIG_ROWS_CACHE_TIME = time.time()
|
|
||||||
|
|
||||||
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()
|
requests = []
|
||||||
ws.clear()
|
column_count = max(len(row) for row in rows)
|
||||||
ws.update(values=rows)
|
if len(rows) > ws.row_count or column_count > ws.col_count:
|
||||||
|
requests.append({"updateSheetProperties": {
|
||||||
# 구글 시트에 저장이 성공하면 로컬 캐시도 즉시 최신화
|
"properties": {"sheetId": ws.id, "gridProperties": {
|
||||||
with _CONFIG_LOCK:
|
"rowCount": max(len(rows), ws.row_count),
|
||||||
_CONFIG_ROWS_CACHE = rows
|
"columnCount": max(column_count, ws.col_count),
|
||||||
_CONFIG_ROWS_CACHE_TIME = time.time()
|
}},
|
||||||
return
|
"fields": "gridProperties(rowCount,columnCount)",
|
||||||
except Exception as e:
|
}})
|
||||||
print(f"Google Sheets 저장 시도 {attempt+1}/3 실패: {e}")
|
# One atomic request replaces values and clears old trailing cells. A
|
||||||
time.sleep(1.5)
|
# timeout between separate clear/update requests must not erase settings.
|
||||||
|
requests.append({"updateCells": {
|
||||||
print("Google Sheets에 설정을 저장하는 데 최종 실패했습니다.")
|
"range": {"sheetId": ws.id},
|
||||||
raise Exception("구글 시트 연동 오류 (할당량 초과). 잠시 후 다시 시도해주세요.")
|
"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 -----
|
||||||
|
|
||||||
@@ -368,8 +373,8 @@ async def index(request: Request):
|
|||||||
version_history = []
|
version_history = []
|
||||||
|
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request=request,
|
request=request,
|
||||||
name="index.html",
|
name="index.html",
|
||||||
context={
|
context={
|
||||||
"version_history": version_history,
|
"version_history": version_history,
|
||||||
"root_path": APP_ROOT_PATH,
|
"root_path": APP_ROOT_PATH,
|
||||||
@@ -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():
|
||||||
config = read_config()
|
if _settings_cache.has_value:
|
||||||
|
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)
|
||||||
@@ -1326,8 +1356,8 @@ async def delete_set_item(item_code: str):
|
|||||||
# ----- 스마트스토어 & 카페24 자동발주 공통 -----
|
# ----- 스마트스토어 & 카페24 자동발주 공통 -----
|
||||||
|
|
||||||
EXCEL_COLUMNS = [
|
EXCEL_COLUMNS = [
|
||||||
'주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량',
|
'주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량',
|
||||||
'주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항',
|
'주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항',
|
||||||
'송장번호', '쇼핑몰명', '비고', '주문번호(쇼핑몰)', '주문목록'
|
'송장번호', '쇼핑몰명', '비고', '주문번호(쇼핑몰)', '주문목록'
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1658,7 +1688,7 @@ async def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str
|
|||||||
fail_list.append(f)
|
fail_list.append(f)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"success_count": success_count,
|
"success_count": success_count,
|
||||||
"fail_count": len(fail_list),
|
"fail_count": len(fail_list),
|
||||||
"fails": fail_list,
|
"fails": fail_list,
|
||||||
|
|||||||
+2
-1
@@ -12,4 +12,5 @@ bcrypt
|
|||||||
requests
|
requests
|
||||||
psycopg2-binary
|
psycopg2-binary
|
||||||
python-dotenv
|
python-dotenv
|
||||||
itsdangerous
|
itsdangerous
|
||||||
|
holidays
|
||||||
|
|||||||
@@ -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
+37
-20
@@ -80,7 +80,7 @@ async def return_lookup(tracking_no: str):
|
|||||||
""", (tracking_no, tracking_no))
|
""", (tracking_no, tracking_no))
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
if row:
|
if row:
|
||||||
return {"success": True, "data": dict(row)}
|
return {"success": True, "data": dict(row)}
|
||||||
return {"success": False, "message": "송장번호를 찾을 수 없습니다."}
|
return {"success": False, "message": "송장번호를 찾을 수 없습니다."}
|
||||||
@@ -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]}
|
||||||
@@ -133,25 +143,25 @@ async def create_return_receive_bulk(req: BulkReturnReceive):
|
|||||||
try:
|
try:
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
today = datetime.now().strftime("%Y-%m-%d")
|
today = datetime.now().strftime("%Y-%m-%d")
|
||||||
|
|
||||||
conn_return = get_return_db_conn()
|
conn_return = get_return_db_conn()
|
||||||
cur_return = conn_return.cursor()
|
cur_return = conn_return.cursor()
|
||||||
|
|
||||||
conn_order = get_order_db_conn()
|
conn_order = get_order_db_conn()
|
||||||
cur_order = conn_order.cursor()
|
cur_order = conn_order.cursor()
|
||||||
|
|
||||||
success_count = 0
|
success_count = 0
|
||||||
|
|
||||||
for tracking_no in req.tracking_numbers:
|
for tracking_no in req.tracking_numbers:
|
||||||
tracking_no = tracking_no.strip()
|
tracking_no = tracking_no.strip()
|
||||||
if not tracking_no:
|
if not tracking_no:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
mall = ""
|
mall = ""
|
||||||
receiver_name = ""
|
receiver_name = ""
|
||||||
phone = ""
|
phone = ""
|
||||||
address = ""
|
address = ""
|
||||||
|
|
||||||
# 1. Check return_requests
|
# 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,))
|
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()
|
req_row = cur_return.fetchone()
|
||||||
@@ -184,7 +194,7 @@ async def create_return_receive_bulk(req: BulkReturnReceive):
|
|||||||
receiver_name = ord_row['recipient_name'] or ""
|
receiver_name = ord_row['recipient_name'] or ""
|
||||||
phone = ord_row['recipient_phone'] or ord_row['recipient_mobile'] or ""
|
phone = ord_row['recipient_phone'] or ord_row['recipient_mobile'] or ""
|
||||||
address = ord_row['address'] or ""
|
address = ord_row['address'] or ""
|
||||||
|
|
||||||
# Insert into return_receivings
|
# Insert into return_receivings
|
||||||
cur_return.execute("""
|
cur_return.execute("""
|
||||||
INSERT INTO return_receivings
|
INSERT INTO return_receivings
|
||||||
@@ -192,11 +202,11 @@ async def create_return_receive_bulk(req: BulkReturnReceive):
|
|||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
""", (today, tracking_no, mall, receiver_name, phone, address, remarks, "환불 대기"))
|
""", (today, tracking_no, mall, receiver_name, phone, address, remarks, "환불 대기"))
|
||||||
success_count += 1
|
success_count += 1
|
||||||
|
|
||||||
conn_return.commit()
|
conn_return.commit()
|
||||||
conn_return.close()
|
conn_return.close()
|
||||||
conn_order.close()
|
conn_order.close()
|
||||||
|
|
||||||
return {"success": True, "count": success_count}
|
return {"success": True, "count": success_count}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Bulk insert error: {e}")
|
print(f"Bulk insert error: {e}")
|
||||||
@@ -208,7 +218,7 @@ async def create_return_receive(req: ReturnReceive):
|
|||||||
req.tracking_no = req.tracking_no.strip()
|
req.tracking_no = req.tracking_no.strip()
|
||||||
conn = get_return_db_conn()
|
conn = get_return_db_conn()
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
|
|
||||||
# 중복 송장 검사
|
# 중복 송장 검사
|
||||||
if req.id:
|
if req.id:
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
@@ -222,7 +232,7 @@ async def create_return_receive(req: ReturnReceive):
|
|||||||
FROM return_receivings
|
FROM return_receivings
|
||||||
WHERE TRIM(tracking_no) = %s
|
WHERE TRIM(tracking_no) = %s
|
||||||
""", (req.tracking_no,))
|
""", (req.tracking_no,))
|
||||||
|
|
||||||
dup = cur.fetchone()
|
dup = cur.fetchone()
|
||||||
if dup:
|
if dup:
|
||||||
conn.close()
|
conn.close()
|
||||||
@@ -231,7 +241,7 @@ async def create_return_receive(req: ReturnReceive):
|
|||||||
"error_type": "duplicate",
|
"error_type": "duplicate",
|
||||||
"data": dict(dup)
|
"data": dict(dup)
|
||||||
}
|
}
|
||||||
|
|
||||||
if not req.id:
|
if not req.id:
|
||||||
cur.execute("SELECT request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (req.tracking_no,))
|
cur.execute("SELECT request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (req.tracking_no,))
|
||||||
req_row = cur.fetchone()
|
req_row = cur.fetchone()
|
||||||
@@ -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
@@ -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; }
|
||||||
+169
-100
@@ -656,7 +656,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
|
|
||||||
// 이름은 한글 2~5글자를 인식하도록 완화
|
// 이름은 한글 2~5글자를 인식하도록 완화
|
||||||
const nameMatch = trimmed.match(/^[가-힣]{2,5}/);
|
const nameMatch = trimmed.match(/^[가-힣]{2,5}/);
|
||||||
|
|
||||||
if (targetField === 'phone') {
|
if (targetField === 'phone') {
|
||||||
const phoneInput = document.getElementById('cust-phone');
|
const phoneInput = document.getElementById('cust-phone');
|
||||||
if (hasPhone) {
|
if (hasPhone) {
|
||||||
@@ -961,7 +961,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
updateOrderGroupBadges();
|
updateOrderGroupBadges();
|
||||||
refreshLiveSmsPreview();
|
refreshLiveSmsPreview();
|
||||||
}
|
}
|
||||||
|
|
||||||
orderItemsContainer.addEventListener('change', function(e) {
|
orderItemsContainer.addEventListener('change', function(e) {
|
||||||
if (e.target.classList.contains('qty-order') && e.target.tagName === 'SELECT' && e.target.value === 'manual') {
|
if (e.target.classList.contains('qty-order') && e.target.tagName === 'SELECT' && e.target.value === 'manual') {
|
||||||
const input = document.createElement('input');
|
const input = document.createElement('input');
|
||||||
@@ -969,7 +969,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
input.min = '1';
|
input.min = '1';
|
||||||
input.value = '1';
|
input.value = '1';
|
||||||
input.className = 'qty-order';
|
input.className = 'qty-order';
|
||||||
|
|
||||||
e.target.replaceWith(input);
|
e.target.replaceWith(input);
|
||||||
input.focus();
|
input.focus();
|
||||||
input.select();
|
input.select();
|
||||||
@@ -1361,13 +1361,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
} else {
|
} else {
|
||||||
itemTotal = cost * qty;
|
itemTotal = cost * qty;
|
||||||
}
|
}
|
||||||
|
|
||||||
const orderType = document.querySelector('input[name="order-type"]:checked').value;
|
const orderType = document.querySelector('input[name="order-type"]:checked').value;
|
||||||
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
||||||
if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) {
|
if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) {
|
||||||
itemTotal = 0;
|
itemTotal = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!excludedIndices.includes(idx)) {
|
if (!excludedIndices.includes(idx)) {
|
||||||
totalCost += itemTotal;
|
totalCost += itemTotal;
|
||||||
if (chk.dataset.isFree === "true") hasMarkedFreeShipping = true;
|
if (chk.dataset.isFree === "true") hasMarkedFreeShipping = true;
|
||||||
@@ -1442,7 +1442,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
|
|
||||||
let baseShippingVal = parseInt((configData.APP_SETTINGS && configData.APP_SETTINGS.shipping_fee) ? configData.APP_SETTINGS.shipping_fee : 3500);
|
let baseShippingVal = parseInt((configData.APP_SETTINGS && configData.APP_SETTINGS.shipping_fee) ? configData.APP_SETTINGS.shipping_fee : 3500);
|
||||||
let extraShippingVal = parseInt((configData.APP_SETTINGS && configData.APP_SETTINGS.extra_shipping_fee) ? configData.APP_SETTINGS.extra_shipping_fee : 3000);
|
let extraShippingVal = parseInt((configData.APP_SETTINGS && configData.APP_SETTINGS.extra_shipping_fee) ? configData.APP_SETTINGS.extra_shipping_fee : 3000);
|
||||||
|
|
||||||
let pointDeduction = parseInt(document.getElementById('sms-point-deduction').value.replace(/,/g, '')) || 0;
|
let pointDeduction = parseInt(document.getElementById('sms-point-deduction').value.replace(/,/g, '')) || 0;
|
||||||
|
|
||||||
let totalAfterDiscount = totalCost;
|
let totalAfterDiscount = totalCost;
|
||||||
@@ -1476,13 +1476,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
else if (hasMarkedFreeShipping) freeReason = "무료배송상품";
|
else if (hasMarkedFreeShipping) freeReason = "무료배송상품";
|
||||||
else freeReason = "무료";
|
else freeReason = "무료";
|
||||||
}
|
}
|
||||||
|
|
||||||
let extraShippingCost = 0;
|
let extraShippingCost = 0;
|
||||||
if (document.getElementById('sms-ship-extra').checked) {
|
if (document.getElementById('sms-ship-extra').checked) {
|
||||||
extraShippingCost = extraShippingVal;
|
extraShippingCost = extraShippingVal;
|
||||||
if (isFreeShip) freeReason += " / 도서산간 추가";
|
if (isFreeShip) freeReason += " / 도서산간 추가";
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentOrderType = document.querySelector('input[name="order-type"]:checked').value;
|
const currentOrderType = document.querySelector('input[name="order-type"]:checked').value;
|
||||||
if (SPECIAL_ORDER_TYPES.has(currentOrderType)) {
|
if (SPECIAL_ORDER_TYPES.has(currentOrderType)) {
|
||||||
shippingCost = 0;
|
shippingCost = 0;
|
||||||
@@ -1539,25 +1539,25 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
// Setup modal
|
// Setup modal
|
||||||
const listContainer = document.getElementById('exclude-items-list');
|
const listContainer = document.getElementById('exclude-items-list');
|
||||||
listContainer.innerHTML = '';
|
listContainer.innerHTML = '';
|
||||||
|
|
||||||
const updateTotalDisplay = () => {
|
const updateTotalDisplay = () => {
|
||||||
const excludedIndices = Array.from(document.querySelectorAll('.exclude-chk:checked')).map(c => parseInt(c.dataset.idx));
|
const excludedIndices = Array.from(document.querySelectorAll('.exclude-chk:checked')).map(c => parseInt(c.dataset.idx));
|
||||||
const livePayload = getOrderPayload(excludedIndices);
|
const livePayload = getOrderPayload(excludedIndices);
|
||||||
|
|
||||||
let displayTotal = livePayload.total_amount;
|
let displayTotal = livePayload.total_amount;
|
||||||
const chkSampleSend = document.getElementById('chk-sample-send');
|
const chkSampleSend = document.getElementById('chk-sample-send');
|
||||||
if (chkSampleSend && chkSampleSend.checked) {
|
if (chkSampleSend && chkSampleSend.checked) {
|
||||||
displayTotal = 0;
|
displayTotal = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('exclude-modal-totalAmount').innerText = displayTotal.toLocaleString();
|
document.getElementById('exclude-modal-totalAmount').innerText = displayTotal.toLocaleString();
|
||||||
|
|
||||||
let extraDiv = document.getElementById('exclude-extra-items');
|
let extraDiv = document.getElementById('exclude-extra-items');
|
||||||
if(!extraDiv) {
|
if(!extraDiv) {
|
||||||
extraDiv = document.createElement('div');
|
extraDiv = document.createElement('div');
|
||||||
extraDiv.id = 'exclude-extra-items';
|
extraDiv.id = 'exclude-extra-items';
|
||||||
}
|
}
|
||||||
|
|
||||||
let extraHTML = '';
|
let extraHTML = '';
|
||||||
if (livePayload.discount_5_amount > 0) {
|
if (livePayload.discount_5_amount > 0) {
|
||||||
extraHTML += `
|
extraHTML += `
|
||||||
@@ -1624,7 +1624,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const qty = parseInt(row.querySelector('.qty-order').value) || 1;
|
const qty = parseInt(row.querySelector('.qty-order').value) || 1;
|
||||||
const multiplier = parseInt(chk.dataset.multiplier) || 1;
|
const multiplier = parseInt(chk.dataset.multiplier) || 1;
|
||||||
const finalQty = qty * multiplier;
|
const finalQty = qty * multiplier;
|
||||||
|
|
||||||
const cost = parseInt(chk.dataset.cost) || 0;
|
const cost = parseInt(chk.dataset.cost) || 0;
|
||||||
const dcost = chk.dataset.dcost === "null" ? null : (parseInt(chk.dataset.dcost) || null);
|
const dcost = chk.dataset.dcost === "null" ? null : (parseInt(chk.dataset.dcost) || null);
|
||||||
let itemTotal = 0;
|
let itemTotal = 0;
|
||||||
@@ -1633,17 +1633,17 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
} else {
|
} else {
|
||||||
itemTotal = cost * qty;
|
itemTotal = cost * qty;
|
||||||
}
|
}
|
||||||
|
|
||||||
const orderType = document.querySelector('input[name="order-type"]:checked').value;
|
const orderType = document.querySelector('input[name="order-type"]:checked').value;
|
||||||
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
||||||
if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) {
|
if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) {
|
||||||
itemTotal = 0;
|
itemTotal = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
let badges = [];
|
let badges = [];
|
||||||
if (SPECIAL_ORDER_TYPES.has(orderType)) badges.push(ORDER_TYPE_LABELS[orderType]);
|
if (SPECIAL_ORDER_TYPES.has(orderType)) badges.push(ORDER_TYPE_LABELS[orderType]);
|
||||||
if (noLidChecked && chk.dataset.type === 'ORDER_SINGLE') badges.push('뚜껑(X)통(O)');
|
if (noLidChecked && chk.dataset.type === 'ORDER_SINGLE') badges.push('뚜껑(X)통(O)');
|
||||||
|
|
||||||
let reasonBadge = badges.length > 0 ? `<span style="font-size:0.75rem; background:#feebc8; color:#dd6b20; padding:2px 5px; border-radius:4px; margin-left:6px; font-weight:bold;">${badges.join(', ')}</span>` : '';
|
let reasonBadge = badges.length > 0 ? `<span style="font-size:0.75rem; background:#feebc8; color:#dd6b20; padding:2px 5px; border-radius:4px; margin-left:6px; font-weight:bold;">${badges.join(', ')}</span>` : '';
|
||||||
|
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
@@ -1654,7 +1654,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
div.style.background = '#fff';
|
div.style.background = '#fff';
|
||||||
div.style.border = '1px solid #cbd5e0';
|
div.style.border = '1px solid #cbd5e0';
|
||||||
div.style.borderRadius = '4px';
|
div.style.borderRadius = '4px';
|
||||||
|
|
||||||
div.innerHTML = `
|
div.innerHTML = `
|
||||||
<label style="cursor:pointer; display:flex; align-items:center; gap:8px; width:100%; margin: 0;">
|
<label style="cursor:pointer; display:flex; align-items:center; gap:8px; width:100%; margin: 0;">
|
||||||
<input type="checkbox" class="exclude-chk" data-idx="${idx}" style="transform: scale(1.2); cursor: pointer;">
|
<input type="checkbox" class="exclude-chk" data-idx="${idx}" style="transform: scale(1.2); cursor: pointer;">
|
||||||
@@ -1662,15 +1662,15 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
<span class="exclude-price-span" style="color:#e53e3e; font-weight:bold; font-size: 0.95rem; transition: opacity 0.2s;">${itemTotal.toLocaleString()}원</span>
|
<span class="exclude-price-span" style="color:#e53e3e; font-weight:bold; font-size: 0.95rem; transition: opacity 0.2s;">${itemTotal.toLocaleString()}원</span>
|
||||||
</label>
|
</label>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const checkbox = div.querySelector('.exclude-chk');
|
const checkbox = div.querySelector('.exclude-chk');
|
||||||
checkbox.addEventListener('change', updateTotalDisplay);
|
checkbox.addEventListener('change', updateTotalDisplay);
|
||||||
|
|
||||||
listContainer.appendChild(div);
|
listContainer.appendChild(div);
|
||||||
});
|
});
|
||||||
|
|
||||||
currentSubmitContext = { url, isEllen };
|
currentSubmitContext = { url, isEllen };
|
||||||
|
|
||||||
const chkSampleSend = document.getElementById('chk-sample-send');
|
const chkSampleSend = document.getElementById('chk-sample-send');
|
||||||
if (chkSampleSend) {
|
if (chkSampleSend) {
|
||||||
chkSampleSend.checked = false;
|
chkSampleSend.checked = false;
|
||||||
@@ -1680,7 +1680,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
updateTotalDisplay();
|
updateTotalDisplay();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
updateTotalDisplay();
|
updateTotalDisplay();
|
||||||
document.getElementById('exclude-modal').style.display = 'flex';
|
document.getElementById('exclude-modal').style.display = 'flex';
|
||||||
}
|
}
|
||||||
@@ -1704,10 +1704,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
|
|
||||||
const isSpecialType = SPECIAL_ORDER_TYPES.has(payload.order_type);
|
const isSpecialType = SPECIAL_ORDER_TYPES.has(payload.order_type);
|
||||||
const typeLabelMap = ORDER_TYPE_LABELS;
|
const typeLabelMap = ORDER_TYPE_LABELS;
|
||||||
|
|
||||||
let finalPayloadAmount = payload.total_amount;
|
let finalPayloadAmount = payload.total_amount;
|
||||||
if (isSpecialType) finalPayloadAmount = 0;
|
if (isSpecialType) finalPayloadAmount = 0;
|
||||||
|
|
||||||
const chkSampleSend = document.getElementById('chk-sample-send');
|
const chkSampleSend = document.getElementById('chk-sample-send');
|
||||||
if (chkSampleSend && chkSampleSend.checked) {
|
if (chkSampleSend && chkSampleSend.checked) {
|
||||||
finalPayloadAmount = 0;
|
finalPayloadAmount = 0;
|
||||||
@@ -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');
|
||||||
@@ -1952,7 +1957,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
} else {
|
} else {
|
||||||
itemTotal = cost * qty;
|
itemTotal = cost * qty;
|
||||||
}
|
}
|
||||||
|
|
||||||
const orderType = document.querySelector('input[name="order-type"]:checked').value;
|
const orderType = document.querySelector('input[name="order-type"]:checked').value;
|
||||||
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
||||||
if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) {
|
if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) {
|
||||||
@@ -2013,12 +2018,12 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
if (!isFreeShip) {
|
if (!isFreeShip) {
|
||||||
shippingCost = baseShippingVal;
|
shippingCost = baseShippingVal;
|
||||||
}
|
}
|
||||||
|
|
||||||
let extraShippingCost = 0;
|
let extraShippingCost = 0;
|
||||||
if (document.getElementById('sms-ship-extra').checked) {
|
if (document.getElementById('sms-ship-extra').checked) {
|
||||||
extraShippingCost = extraShippingVal;
|
extraShippingCost = extraShippingVal;
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentOrderType = document.querySelector('input[name="order-type"]:checked').value;
|
const currentOrderType = document.querySelector('input[name="order-type"]:checked').value;
|
||||||
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
const noLidChecked = document.getElementById('chk-no-lid').checked;
|
||||||
if (SPECIAL_ORDER_TYPES.has(currentOrderType) || noLidChecked) {
|
if (SPECIAL_ORDER_TYPES.has(currentOrderType) || noLidChecked) {
|
||||||
@@ -2202,11 +2207,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const name = firstNonEmpty(d.custName, d.customer_name, cachedCustomer.custName, cachedCustomer.customer_name);
|
const name = firstNonEmpty(d.custName, d.customer_name, cachedCustomer.custName, cachedCustomer.customer_name);
|
||||||
const phone = firstNonEmpty(d.custPhone, d.phone, cachedCustomer.custPhone, cachedCustomer.phone);
|
const phone = firstNonEmpty(d.custPhone, d.phone, cachedCustomer.custPhone, cachedCustomer.phone);
|
||||||
const address = firstNonEmpty(d.custAddress, d.address, cachedCustomer.custAddress, cachedCustomer.address);
|
const address = firstNonEmpty(d.custAddress, d.address, cachedCustomer.custAddress, cachedCustomer.address);
|
||||||
|
|
||||||
const hasCustInfo = (name && name.trim() && name.trim().toLowerCase() !== 'none') ||
|
const hasCustInfo = (name && name.trim() && name.trim().toLowerCase() !== 'none') ||
|
||||||
(phone && phone.trim() && phone.trim().toLowerCase() !== 'none') ||
|
(phone && phone.trim() && phone.trim().toLowerCase() !== 'none') ||
|
||||||
(address && address.trim() && address.trim().toLowerCase() !== 'none');
|
(address && address.trim() && address.trim().toLowerCase() !== 'none');
|
||||||
|
|
||||||
let amountStr = d.deposit_amount_str || '';
|
let amountStr = d.deposit_amount_str || '';
|
||||||
if (hasCustInfo) {
|
if (hasCustInfo) {
|
||||||
amountStr = amountStr.replace('원', '원*');
|
amountStr = amountStr.replace('원', '원*');
|
||||||
@@ -2523,10 +2528,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
|
|
||||||
let baseShippingVal = data['APP_SETTINGS'] && data['APP_SETTINGS']['shipping_fee'] ? data['APP_SETTINGS']['shipping_fee'] : '3500';
|
let baseShippingVal = data['APP_SETTINGS'] && data['APP_SETTINGS']['shipping_fee'] ? data['APP_SETTINGS']['shipping_fee'] : '3500';
|
||||||
let extraShippingVal = data['APP_SETTINGS'] && data['APP_SETTINGS']['extra_shipping_fee'] ? data['APP_SETTINGS']['extra_shipping_fee'] : '3000';
|
let extraShippingVal = data['APP_SETTINGS'] && data['APP_SETTINGS']['extra_shipping_fee'] ? data['APP_SETTINGS']['extra_shipping_fee'] : '3000';
|
||||||
|
|
||||||
document.getElementById('setting-ship-base').value = parseInt(baseShippingVal).toLocaleString();
|
document.getElementById('setting-ship-base').value = parseInt(baseShippingVal).toLocaleString();
|
||||||
document.getElementById('setting-ship-extra').value = parseInt(extraShippingVal).toLocaleString();
|
document.getElementById('setting-ship-extra').value = parseInt(extraShippingVal).toLocaleString();
|
||||||
|
|
||||||
const lblShipExtra = document.getElementById('lbl-ship-extra');
|
const lblShipExtra = document.getElementById('lbl-ship-extra');
|
||||||
if (lblShipExtra) {
|
if (lblShipExtra) {
|
||||||
lblShipExtra.textContent = '추가배송비 ' + parseInt(extraShippingVal).toLocaleString() + '원';
|
lblShipExtra.textContent = '추가배송비 ' + parseInt(extraShippingVal).toLocaleString() + '원';
|
||||||
@@ -2596,7 +2601,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
if (fText) payload.rules['footer_text'] = fText.value;
|
if (fText) payload.rules['footer_text'] = fText.value;
|
||||||
const fontSel = document.getElementById('app-font-select');
|
const fontSel = document.getElementById('app-font-select');
|
||||||
if (fontSel) payload.app_settings.font = fontSel.value;
|
if (fontSel) payload.app_settings.font = fontSel.value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/gift/settings', {
|
const res = await fetch('/api/gift/settings', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -2786,7 +2791,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
alert('송장 앞 숫자 저장에 실패했습니다.');
|
alert('송장 앞 숫자 저장에 실패했습니다.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const trackingNumbers = lines.map(l => {
|
const trackingNumbers = lines.map(l => {
|
||||||
let val = l.trim();
|
let val = l.trim();
|
||||||
if (val && savedPrefix && val.length === 8) {
|
if (val && savedPrefix && val.length === 8) {
|
||||||
@@ -2794,7 +2799,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
return val;
|
return val;
|
||||||
}).filter(l => l);
|
}).filter(l => l);
|
||||||
|
|
||||||
if (trackingNumbers.length === 0) {
|
if (trackingNumbers.length === 0) {
|
||||||
alert('송장번호를 입력해주세요.');
|
alert('송장번호를 입력해주세요.');
|
||||||
return;
|
return;
|
||||||
@@ -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 || '';
|
||||||
@@ -2896,8 +2919,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
`;
|
`;
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
const chkAll = document.getElementById('chk-all-req');
|
const chkAll = document.getElementById('chk-all-req');
|
||||||
if (chkAll) {
|
if (chkAll) {
|
||||||
chkAll.checked = false;
|
chkAll.checked = false;
|
||||||
@@ -2905,7 +2928,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
document.querySelectorAll('.chk-req-row').forEach(cb => cb.checked = e.target.checked);
|
document.querySelectorAll('.chk-req-row').forEach(cb => cb.checked = e.target.checked);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
document.querySelectorAll('.btn-delete-req').forEach(btn => {
|
document.querySelectorAll('.btn-delete-req').forEach(btn => {
|
||||||
btn.addEventListener('click', async (e) => {
|
btn.addEventListener('click', async (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
@@ -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';
|
||||||
@@ -2976,7 +3010,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
`;
|
`;
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('.btn-delete-rec').forEach(btn => {
|
document.querySelectorAll('.btn-delete-rec').forEach(btn => {
|
||||||
btn.addEventListener('click', async (e) => {
|
btn.addEventListener('click', async (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
@@ -2993,12 +3027,47 @@ 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');
|
||||||
if (chkExcludeCompleted) {
|
if (chkExcludeCompleted) {
|
||||||
chkExcludeCompleted.addEventListener('change', () => {
|
chkExcludeCompleted.addEventListener('change', () => {
|
||||||
@@ -3012,13 +3081,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
loadReturnRequests();
|
loadReturnRequests();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if(returnTabMenu) {
|
if(returnTabMenu) {
|
||||||
returnTabMenu.addEventListener('click', () => {
|
returnTabMenu.addEventListener('click', () => {
|
||||||
loadReturnRequests();
|
loadReturnRequests();
|
||||||
loadReturnReceivings();
|
loadReturnReceivings();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Load immediately on page load
|
// Load immediately on page load
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
loadReturnRequests();
|
loadReturnRequests();
|
||||||
@@ -3027,7 +3096,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
const reqTrackingNo = document.getElementById('req-tracking-no');
|
const reqTrackingNo = document.getElementById('req-tracking-no');
|
||||||
const recTrackingNo = document.getElementById('rec-tracking-no');
|
const recTrackingNo = document.getElementById('rec-tracking-no');
|
||||||
|
|
||||||
// Auto-paste 12-digit tracking number on click
|
// Auto-paste 12-digit tracking number on click
|
||||||
async function handleTrackingClick(e) {
|
async function handleTrackingClick(e) {
|
||||||
try {
|
try {
|
||||||
@@ -3043,11 +3112,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
console.log('Clipboard read failed: ', err);
|
console.log('Clipboard read failed: ', err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (reqTrackingNo) reqTrackingNo.addEventListener('click', handleTrackingClick);
|
if (reqTrackingNo) reqTrackingNo.addEventListener('click', handleTrackingClick);
|
||||||
if (recTrackingNo) recTrackingNo.addEventListener('click', handleTrackingClick);
|
if (recTrackingNo) recTrackingNo.addEventListener('click', handleTrackingClick);
|
||||||
|
|
||||||
|
|
||||||
// Default dates to today
|
// Default dates to today
|
||||||
const reqDate = document.getElementById('req-date');
|
const reqDate = document.getElementById('req-date');
|
||||||
if (reqDate) reqDate.value = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0];
|
if (reqDate) reqDate.value = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0];
|
||||||
@@ -3103,7 +3172,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
foundInReq = true;
|
foundInReq = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If not found in requests, fallback to orderlist_app
|
// If not found in requests, fallback to orderlist_app
|
||||||
if(!foundInReq) {
|
if(!foundInReq) {
|
||||||
const res2 = await fetch('/api/return/lookup?tracking_no=' + encodeURIComponent(no));
|
const res2 = await fetch('/api/return/lookup?tracking_no=' + encodeURIComponent(no));
|
||||||
@@ -3495,7 +3564,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================
|
// ============================================
|
||||||
// CODE TAB (Master Data Mgmt)
|
// CODE TAB (Master Data Mgmt)
|
||||||
// ============================================
|
// ============================================
|
||||||
@@ -3522,7 +3591,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const renderSingleItems = () => {
|
const renderSingleItems = () => {
|
||||||
const tbody = document.getElementById('single-items-tbody');
|
const tbody = document.getElementById('single-items-tbody');
|
||||||
tbody.innerHTML = '';
|
tbody.innerHTML = '';
|
||||||
|
|
||||||
singleItemsList.sort((a,b) => {
|
singleItemsList.sort((a,b) => {
|
||||||
let valA = a[singleSort.key] || '';
|
let valA = a[singleSort.key] || '';
|
||||||
let valB = b[singleSort.key] || '';
|
let valB = b[singleSort.key] || '';
|
||||||
@@ -3556,7 +3625,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
`;
|
`;
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('.th-sortable[data-list="single"]').forEach(th => {
|
document.querySelectorAll('.th-sortable[data-list="single"]').forEach(th => {
|
||||||
const icon = th.querySelector('.sort-icon');
|
const icon = th.querySelector('.sort-icon');
|
||||||
if(!icon) return;
|
if(!icon) return;
|
||||||
@@ -3580,7 +3649,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const renderSetItems = () => {
|
const renderSetItems = () => {
|
||||||
const tbody = document.getElementById('set-items-tbody');
|
const tbody = document.getElementById('set-items-tbody');
|
||||||
tbody.innerHTML = '';
|
tbody.innerHTML = '';
|
||||||
|
|
||||||
let tooltip = document.getElementById('set-comp-tooltip');
|
let tooltip = document.getElementById('set-comp-tooltip');
|
||||||
if (!tooltip) {
|
if (!tooltip) {
|
||||||
tooltip = document.createElement('div');
|
tooltip = document.createElement('div');
|
||||||
@@ -3598,7 +3667,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
tooltip.style.gap = '2px';
|
tooltip.style.gap = '2px';
|
||||||
document.body.appendChild(tooltip);
|
document.body.appendChild(tooltip);
|
||||||
}
|
}
|
||||||
|
|
||||||
const mapCompInfo = c => {
|
const mapCompInfo = c => {
|
||||||
const sInfo = singleItemsList.find(s => s.item_code === c.single_code);
|
const sInfo = singleItemsList.find(s => s.item_code === c.single_code);
|
||||||
let displayName = sInfo ? sInfo.name : c.single_code;
|
let displayName = sInfo ? sInfo.name : c.single_code;
|
||||||
@@ -3610,7 +3679,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const textColor = isHwangto ? 'color:#c05621;' : '';
|
const textColor = isHwangto ? 'color:#c05621;' : '';
|
||||||
return `<span class="comp-span" style="display:inline-block; ${bg} ${border} padding:1px 4px; border-radius:3px; font-size:0.75rem; margin:1px; ${textColor}">${displayName} <b style="color:${qtyColor};">${c.quantity}</b></span>`;
|
return `<span class="comp-span" style="display:inline-block; ${bg} ${border} padding:1px 4px; border-radius:3px; font-size:0.75rem; margin:1px; ${textColor}">${displayName} <b style="color:${qtyColor};">${c.quantity}</b></span>`;
|
||||||
};
|
};
|
||||||
|
|
||||||
setItemsList.sort((a,b) => {
|
setItemsList.sort((a,b) => {
|
||||||
let valA = a[setSort.key] || '';
|
let valA = a[setSort.key] || '';
|
||||||
let valB = b[setSort.key] || '';
|
let valB = b[setSort.key] || '';
|
||||||
@@ -3627,9 +3696,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
tr.className = 'hover-row';
|
tr.className = 'hover-row';
|
||||||
tr.style.height = '27px';
|
tr.style.height = '27px';
|
||||||
tr.style.borderBottom = '1px solid #e2e8f0';
|
tr.style.borderBottom = '1px solid #e2e8f0';
|
||||||
|
|
||||||
const compsHtml = item.components.map(mapCompInfo).join('');
|
const compsHtml = item.components.map(mapCompInfo).join('');
|
||||||
|
|
||||||
tr.innerHTML = `
|
tr.innerHTML = `
|
||||||
<td style="padding: 0 10px; font-weight:bold; font-size: 0.85rem;">${item.item_code}</td>
|
<td style="padding: 0 10px; font-weight:bold; font-size: 0.85rem;">${item.item_code}</td>
|
||||||
<td style="padding: 0 10px; font-size: 0.85rem; white-space: nowrap;">${item.name || ''}</td>
|
<td style="padding: 0 10px; font-size: 0.85rem; white-space: nowrap;">${item.name || ''}</td>
|
||||||
@@ -3653,7 +3722,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
tr._itemComps = item.components;
|
tr._itemComps = item.components;
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 모든 행이 그려진 후 브라우저가 그리드를 계산할 여유를 주기 위해 지연실행
|
// 모든 행이 그려진 후 브라우저가 그리드를 계산할 여유를 주기 위해 지연실행
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const rows = tbody.querySelectorAll('tr');
|
const rows = tbody.querySelectorAll('tr');
|
||||||
@@ -3666,7 +3735,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
if (spans.length > 0) {
|
if (spans.length > 0) {
|
||||||
let hiddenCount = 0;
|
let hiddenCount = 0;
|
||||||
let lastVisibleIndex = spans.length - 1;
|
let lastVisibleIndex = spans.length - 1;
|
||||||
|
|
||||||
// X좌표를 기준으로 컨테이너를 벗어나는 아이템 탐색
|
// X좌표를 기준으로 컨테이너를 벗어나는 아이템 탐색
|
||||||
const maxLimit = wrapper.offsetWidth - 48; // 오른쪽 48px는 '외 N개' 표기를 위해 예약
|
const maxLimit = wrapper.offsetWidth - 48; // 오른쪽 48px는 '외 N개' 표기를 위해 예약
|
||||||
for (let i = 0; i < spans.length; i++) {
|
for (let i = 0; i < spans.length; i++) {
|
||||||
@@ -3678,11 +3747,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
|
|
||||||
if (lastVisibleIndex < spans.length - 1 && lastVisibleIndex >= 0) {
|
if (lastVisibleIndex < spans.length - 1 && lastVisibleIndex >= 0) {
|
||||||
hiddenCount = spans.length - 1 - lastVisibleIndex;
|
hiddenCount = spans.length - 1 - lastVisibleIndex;
|
||||||
|
|
||||||
for (let i = lastVisibleIndex + 1; i < spans.length; i++) {
|
for (let i = lastVisibleIndex + 1; i < spans.length; i++) {
|
||||||
spans[i].style.display = 'none';
|
spans[i].style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
indicator.innerText = `외 ${hiddenCount}개`;
|
indicator.innerText = `외 ${hiddenCount}개`;
|
||||||
indicator.style.display = 'inline-block';
|
indicator.style.display = 'inline-block';
|
||||||
} else if (lastVisibleIndex < 0 && spans.length > 1) {
|
} else if (lastVisibleIndex < 0 && spans.length > 1) {
|
||||||
@@ -3694,7 +3763,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
indicator.innerText = `외 ${hiddenCount}개`;
|
indicator.innerText = `외 ${hiddenCount}개`;
|
||||||
indicator.style.display = 'inline-block';
|
indicator.style.display = 'inline-block';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hiddenCount > 0 && tr._itemComps) {
|
if (hiddenCount > 0 && tr._itemComps) {
|
||||||
const compsCell = tr.querySelector('.comps-cell');
|
const compsCell = tr.querySelector('.comps-cell');
|
||||||
compsCell.addEventListener('mouseenter', (e) => {
|
compsCell.addEventListener('mouseenter', (e) => {
|
||||||
@@ -3719,7 +3788,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, 50);
|
}, 50);
|
||||||
|
|
||||||
document.querySelectorAll('.th-sortable[data-list="set"]').forEach(th => {
|
document.querySelectorAll('.th-sortable[data-list="set"]').forEach(th => {
|
||||||
const icon = th.querySelector('.sort-icon');
|
const icon = th.querySelector('.sort-icon');
|
||||||
if(!icon) return;
|
if(!icon) return;
|
||||||
@@ -3815,7 +3884,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const btnDelSet = e.target.closest('.btn-del-set');
|
const btnDelSet = e.target.closest('.btn-del-set');
|
||||||
if(btnDelSet) {
|
if(btnDelSet) {
|
||||||
if(confirm('세트 항목을 삭제하시겠습니까?')) {
|
if(confirm('세트 항목을 삭제하시겠습니까?')) {
|
||||||
@@ -3823,7 +3892,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const btnEditSin = e.target.closest('.btn-edit-sin');
|
const btnEditSin = e.target.closest('.btn-edit-sin');
|
||||||
if(btnEditSin) {
|
if(btnEditSin) {
|
||||||
const code = btnEditSin.dataset.code;
|
const code = btnEditSin.dataset.code;
|
||||||
@@ -3863,7 +3932,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
// Single Modal
|
// Single Modal
|
||||||
const sinItemCodeInput = document.getElementById('sin-item-code');
|
const sinItemCodeInput = document.getElementById('sin-item-code');
|
||||||
const sinItemWarn = document.getElementById('sin-item-warn');
|
const sinItemWarn = document.getElementById('sin-item-warn');
|
||||||
|
|
||||||
sinItemCodeInput.addEventListener('input', (e) => {
|
sinItemCodeInput.addEventListener('input', (e) => {
|
||||||
let val = e.target.value.toUpperCase();
|
let val = e.target.value.toUpperCase();
|
||||||
e.target.value = val;
|
e.target.value = val;
|
||||||
@@ -3896,7 +3965,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
let sabangnet = document.getElementById('sin-sabangnet-code').value.trim();
|
let sabangnet = document.getElementById('sin-sabangnet-code').value.trim();
|
||||||
const name = document.getElementById('sin-name').value.trim();
|
const name = document.getElementById('sin-name').value.trim();
|
||||||
if(!itemCode || !sabangnet || !name) { alert('모든 항목을 입력해주세요.'); return; }
|
if(!itemCode || !sabangnet || !name) { alert('모든 항목을 입력해주세요.'); return; }
|
||||||
|
|
||||||
if (itemCode.length > 0 && !/^[A-Z]/.test(itemCode)) {
|
if (itemCode.length > 0 && !/^[A-Z]/.test(itemCode)) {
|
||||||
alert('아이템 코드의 첫 글자는 반드시 영문이어야 합니다!');
|
alert('아이템 코드의 첫 글자는 반드시 영문이어야 합니다!');
|
||||||
return;
|
return;
|
||||||
@@ -3907,11 +3976,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(!sabangnet.endsWith('-0001')) sabangnet += '-0001';
|
if(!sabangnet.endsWith('-0001')) sabangnet += '-0001';
|
||||||
|
|
||||||
const payload = {item_code: itemCode, sabangnet_code: sabangnet, name: name};
|
const payload = {item_code: itemCode, sabangnet_code: sabangnet, name: name};
|
||||||
const method = editingSingleCode ? 'PUT' : 'POST';
|
const method = editingSingleCode ? 'PUT' : 'POST';
|
||||||
const url = editingSingleCode ? '/api/codes/single/' + encodeURIComponent(editingSingleCode) : '/api/codes/single';
|
const url = editingSingleCode ? '/api/codes/single/' + encodeURIComponent(editingSingleCode) : '/api/codes/single';
|
||||||
|
|
||||||
fetch(url, {
|
fetch(url, {
|
||||||
method: method, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
|
method: method, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
|
||||||
}).then(r => r.json()).then(res => {
|
}).then(r => r.json()).then(res => {
|
||||||
@@ -3922,7 +3991,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Single sabangnet auto append -0001 on blur
|
// Single sabangnet auto append -0001 on blur
|
||||||
document.getElementById('sin-sabangnet-code').addEventListener('blur', (e) => {
|
document.getElementById('sin-sabangnet-code').addEventListener('blur', (e) => {
|
||||||
let val = e.target.value.trim();
|
let val = e.target.value.trim();
|
||||||
@@ -3934,7 +4003,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
// Set Modal
|
// Set Modal
|
||||||
const setItemCodeInput = document.getElementById('set-item-code');
|
const setItemCodeInput = document.getElementById('set-item-code');
|
||||||
const setItemWarn = document.getElementById('set-item-warn');
|
const setItemWarn = document.getElementById('set-item-warn');
|
||||||
|
|
||||||
setItemCodeInput.addEventListener('input', (e) => {
|
setItemCodeInput.addEventListener('input', (e) => {
|
||||||
let val = e.target.value.toUpperCase();
|
let val = e.target.value.toUpperCase();
|
||||||
e.target.value = val;
|
e.target.value = val;
|
||||||
@@ -3954,7 +4023,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
div.style.display = 'flex';
|
div.style.display = 'flex';
|
||||||
div.style.gap = '5px';
|
div.style.gap = '5px';
|
||||||
div.style.alignItems = 'center';
|
div.style.alignItems = 'center';
|
||||||
|
|
||||||
let optionsHtml = '<option value="">단품코드 선택</option>';
|
let optionsHtml = '<option value="">단품코드 선택</option>';
|
||||||
singleItemsList.forEach(s => {
|
singleItemsList.forEach(s => {
|
||||||
const selected = (s.item_code === sc) ? 'selected' : '';
|
const selected = (s.item_code === sc) ? 'selected' : '';
|
||||||
@@ -3974,7 +4043,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
div.querySelector('.comp-del').addEventListener('click', () => div.remove());
|
div.querySelector('.comp-del').addEventListener('click', () => div.remove());
|
||||||
document.getElementById('set-components-wrapper').appendChild(div);
|
document.getElementById('set-components-wrapper').appendChild(div);
|
||||||
};
|
};
|
||||||
|
|
||||||
btnAddSet.addEventListener('click', () => {
|
btnAddSet.addEventListener('click', () => {
|
||||||
editingSetCode = null;
|
editingSetCode = null;
|
||||||
document.getElementById('modal-set-title').innerText = '🍱 새 세트 추가';
|
document.getElementById('modal-set-title').innerText = '🍱 새 세트 추가';
|
||||||
@@ -3996,17 +4065,17 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const itemCode = document.getElementById('set-item-code').value.trim();
|
const itemCode = document.getElementById('set-item-code').value.trim();
|
||||||
const name = document.getElementById('set-name').value.trim();
|
const name = document.getElementById('set-name').value.trim();
|
||||||
if(!itemCode) { alert('세트 아이템 코드를 입력해주세요.'); return; }
|
if(!itemCode) { alert('세트 아이템 코드를 입력해주세요.'); return; }
|
||||||
|
|
||||||
if (itemCode.length > 0 && !/^[A-Z]/.test(itemCode)) {
|
if (itemCode.length > 0 && !/^[A-Z]/.test(itemCode)) {
|
||||||
alert('아이템 코드의 첫 글자는 반드시 영문이어야 합니다!');
|
alert('아이템 코드의 첫 글자는 반드시 영문이어야 합니다!');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!editingSetCode && setItemsList.some(s => s.item_code === itemCode)) {
|
if(!editingSetCode && setItemsList.some(s => s.item_code === itemCode)) {
|
||||||
alert('이미 존재하는 세트 아이템 코드입니다!');
|
alert('이미 존재하는 세트 아이템 코드입니다!');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const components = [];
|
const components = [];
|
||||||
const rows = document.getElementById('set-components-wrapper').querySelectorAll(':scope > div');
|
const rows = document.getElementById('set-components-wrapper').querySelectorAll(':scope > div');
|
||||||
rows.forEach(r => {
|
rows.forEach(r => {
|
||||||
@@ -4020,13 +4089,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if(components.length === 0) { alert('유효한 단품 구성품을 최소 1개 이상 선택해주세요.'); return; }
|
if(components.length === 0) { alert('유효한 단품 구성품을 최소 1개 이상 선택해주세요.'); return; }
|
||||||
|
|
||||||
const payload = {item_code: itemCode, components: components, sabangnet_code: "", name: name};
|
const payload = {item_code: itemCode, components: components, sabangnet_code: "", name: name};
|
||||||
const method = editingSetCode ? 'PUT' : 'POST';
|
const method = editingSetCode ? 'PUT' : 'POST';
|
||||||
const url = editingSetCode ? '/api/codes/set/' + encodeURIComponent(editingSetCode) : '/api/codes/set';
|
const url = editingSetCode ? '/api/codes/set/' + encodeURIComponent(editingSetCode) : '/api/codes/set';
|
||||||
|
|
||||||
fetch(url, {
|
fetch(url, {
|
||||||
method: method, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
|
method: method, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
|
||||||
}).then(r => r.json()).then(res => {
|
}).then(r => r.json()).then(res => {
|
||||||
@@ -4061,7 +4130,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
alert('이메일로 보낼 반품 신청 항목을 선택해주세요.');
|
alert('이메일로 보낼 반품 신청 항목을 선택해주세요.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const d = new Date();
|
const d = new Date();
|
||||||
const yyyy = d.getFullYear();
|
const yyyy = d.getFullYear();
|
||||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
@@ -4069,7 +4138,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const days = ['일', '월', '화', '수', '목', '금', '토'];
|
const days = ['일', '월', '화', '수', '목', '금', '토'];
|
||||||
const dow = days[d.getDay()];
|
const dow = days[d.getDay()];
|
||||||
const subject = `★ ${yyyy}년 ${m}월 ${dd}일(${dow}) 미라네주방 반품 신청`;
|
const subject = `★ ${yyyy}년 ${m}월 ${dd}일(${dow}) 미라네주방 반품 신청`;
|
||||||
|
|
||||||
let plainTextGreeting = "안녕하세요.\r\n오늘 반품 신청합니다.\r\n내용은 아래와 같습니다.\r\n감사합니다.\r\n\r\n";
|
let plainTextGreeting = "안녕하세요.\r\n오늘 반품 신청합니다.\r\n내용은 아래와 같습니다.\r\n감사합니다.\r\n\r\n";
|
||||||
let ptIndex = 1;
|
let ptIndex = 1;
|
||||||
checkedBoxes.forEach(cb => {
|
checkedBoxes.forEach(cb => {
|
||||||
@@ -4085,8 +4154,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
ptIndex++;
|
ptIndex++;
|
||||||
} catch(e) {}
|
} catch(e) {}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
let htmlTable = `
|
let htmlTable = `
|
||||||
<table border="1" style="border-collapse: collapse; font-family: '맑은 고딕', sans-serif; font-size: 10pt; text-align: center;">
|
<table border="1" style="border-collapse: collapse; font-family: '맑은 고딕', sans-serif; font-size: 10pt; text-align: center;">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -4100,7 +4169,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
let index = 1;
|
let index = 1;
|
||||||
checkedBoxes.forEach(cb => {
|
checkedBoxes.forEach(cb => {
|
||||||
try {
|
try {
|
||||||
@@ -4122,7 +4191,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
} catch(e) {}
|
} catch(e) {}
|
||||||
});
|
});
|
||||||
htmlTable += `</tbody></table>`;
|
htmlTable += `</tbody></table>`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const blobHtml = new Blob([htmlTable], { type: 'text/html' });
|
const blobHtml = new Blob([htmlTable], { type: 'text/html' });
|
||||||
const blobText = new Blob(["표가 클립보드에 복사되었습니다. 메일 본문에 붙여넣기 하세요."], { type: 'text/plain' });
|
const blobText = new Blob(["표가 클립보드에 복사되었습니다. 메일 본문에 붙여넣기 하세요."], { type: 'text/plain' });
|
||||||
@@ -4154,7 +4223,7 @@ function handleFormEmptyClick(e, formId) {
|
|||||||
// If the click is on an input, select, button, label, or textarea, do nothing
|
// If the click is on an input, select, button, label, or textarea, do nothing
|
||||||
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT' || e.target.tagName === 'BUTTON' || e.target.tagName === 'LABEL' || e.target.tagName === 'TEXTAREA') return;
|
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT' || e.target.tagName === 'BUTTON' || e.target.tagName === 'LABEL' || e.target.tagName === 'TEXTAREA') return;
|
||||||
if (e.target.closest('button')) return;
|
if (e.target.closest('button')) return;
|
||||||
|
|
||||||
// Otherwise it's an empty space click
|
// Otherwise it's an empty space click
|
||||||
const form = document.getElementById(formId);
|
const form = document.getElementById(formId);
|
||||||
if (form) {
|
if (form) {
|
||||||
@@ -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();
|
||||||
@@ -4201,17 +4270,17 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
if (updateModal) {
|
if (updateModal) {
|
||||||
document.getElementById('update-notice-version').textContent = CURRENT_APP_VERSION;
|
document.getElementById('update-notice-version').textContent = CURRENT_APP_VERSION;
|
||||||
const storageKey = `hide_update_popup_${CURRENT_APP_VERSION}`;
|
const storageKey = `hide_update_popup_${CURRENT_APP_VERSION}`;
|
||||||
|
|
||||||
if (localStorage.getItem(storageKey) !== 'true') {
|
if (localStorage.getItem(storageKey) !== 'true') {
|
||||||
updateModal.style.display = 'flex';
|
updateModal.style.display = 'flex';
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('btn-close-update-notice').addEventListener('click', () => {
|
document.getElementById('btn-close-update-notice').addEventListener('click', () => {
|
||||||
if (document.getElementById('chk-hide-update-notice').checked) {
|
if (document.getElementById('chk-hide-update-notice').checked) {
|
||||||
localStorage.setItem(storageKey, 'true');
|
localStorage.setItem(storageKey, 'true');
|
||||||
}
|
}
|
||||||
updateModal.style.display = 'none';
|
updateModal.style.display = 'none';
|
||||||
|
|
||||||
// Switch to Version History tab
|
// Switch to Version History tab
|
||||||
const historyTab = document.querySelector('[data-tab="version-history-tab"]');
|
const historyTab = document.querySelector('[data-tab="version-history-tab"]');
|
||||||
if (historyTab) {
|
if (historyTab) {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
|||||||
// 쿠팡 밀크런 캘린더
|
// 쿠팡 밀크런 캘린더
|
||||||
//
|
//
|
||||||
// 화면이 열리면 구글 드라이브의 밀크런 출고리스트를 자동으로 읽어
|
// 밀크런 탭을 열었을 때만 구글 드라이브의 밀크런 출고리스트를 읽어
|
||||||
// 시트 이름(YYYYMMDD)을 달력에 표시한다.
|
// 시트 이름(YYYYMMDD)을 달력에 표시한다. 메인 화면 로딩 중에는
|
||||||
|
// 구글 시트 조회나 분석 요청을 실행하지 않는다.
|
||||||
// 달력에서 날짜를 고르면 그 시트의 제품코드/제품명/수량을 읽어
|
// 달력에서 날짜를 고르면 그 시트의 제품코드/제품명/수량을 읽어
|
||||||
// 붙여넣기 입력을 채우고 곧바로 분석까지 실행한다.
|
// 붙여넣기 입력을 채우고 곧바로 분석까지 실행한다.
|
||||||
// (시트 주소는 서버에 설정되어 있어 화면에서 입력하지 않는다)
|
// (시트 주소는 서버에 설정되어 있어 화면에서 입력하지 않는다)
|
||||||
@@ -356,8 +357,8 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 달력 틀을 먼저 보여주고(덮개가 '읽는 중'을 표시), 출고일은 뒤이어 채운다
|
// 초기 화면에서는 달력 틀만 준비한다. 실제 조회와 분석은 위의
|
||||||
renderCalendar();
|
// 밀크런 메뉴 클릭 이벤트에서만 시작한다.
|
||||||
loadSheetTabs(false);
|
renderCalendar('밀크런 탭을 열면 출고일을 불러옵니다');
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
+276
-6
@@ -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
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -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",
|
||||||
|
|||||||
Reference in New Issue
Block a user