diff --git a/.dockerignore b/.dockerignore index 5a3e8f9..8386363 100644 --- a/.dockerignore +++ b/.dockerignore @@ -37,3 +37,6 @@ deploy.ps1 start.bat test.ps1 *.xlsx + +# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache) +.cache/ diff --git a/.env.example b/.env.example index 3f6d680..318539b 100644 --- a/.env.example +++ b/.env.example @@ -66,3 +66,20 @@ INTERNAL_SERVICE_TOKEN=__paste-same-value-as-dbx-orderlist__ # ============================================ POSTGRES_NETWORK=postgres_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 diff --git a/.gitignore b/.gitignore index bf07813..8e48c1d 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,6 @@ deploy.bat deploy.ps1 start.bat test.ps1 + +# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache) +.cache/ diff --git a/README.md b/README.md index 4b751ce..ec03d50 100644 --- a/README.md +++ b/README.md @@ -18,12 +18,19 @@ FastAPI + PostgreSQL 기반, Docker로 실행. | 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` | 주문 정보 조회 | | `return_db` | 반품 데이터 저장 | 모두 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`) diff --git a/google_runtime.py b/google_runtime.py new file mode 100644 index 0000000..6d953f9 --- /dev/null +++ b/google_runtime.py @@ -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) diff --git a/main.py b/main.py index 2f8beee..31ad0f2 100644 --- a/main.py +++ b/main.py @@ -10,11 +10,11 @@ import io import math import datetime import configparser -import threading import urllib.request import urllib.parse import uuid import secrets +import threading from urllib.parse import quote from dotenv import load_dotenv from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks @@ -32,6 +32,10 @@ from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from typing import List, Optional, Dict, Any +from google_runtime import ( + GOOGLE_READ_TIMEOUT, GoogleTimeoutSession, SettingsCache, + create_google_client, google_worker, history_access, run_google_io, settings_update, +) # ========================================== # SSO / 서브경로 호스팅 설정 @@ -213,6 +217,9 @@ app.include_router(coupang_milkrun_router) from routers.mall_event import router as mall_event_router app.include_router(mall_event_router) +from routers.cs_records import router as cs_records_router, add_special_order_records +app.include_router(cs_records_router) + # Ensure directories exist os.makedirs("static/css", exist_ok=True) os.makedirs("static/js", exist_ok=True) @@ -230,6 +237,11 @@ MANUAL_SPREADSHEET_ID = os.getenv('MANUAL_SPREADSHEET_ID', '1QxFtjDurPPZd8NmtXBy SETTINGS_SPREADSHEET_ID = os.getenv('SETTINGS_SPREADSHEET_ID', '1k7SNEdIaRtGXzQNdJSQAiNSDRwzOePDRTLHY_mNCO8M') MANUAL_HISTORY_FILE = os.getenv('MANUAL_HISTORY_FILE', os.path.join(BASE_DIR, 'manual_history.dat')) SMS_HISTORY_HEADERS = ["일시", "주문유형", "입금액", "주문아이템", "메시지 내용", "이름", "연락처", "주소"] +_settings_cache = SettingsCache( + os.getenv("SETTINGS_CACHE_FILE", os.path.join(BASE_DIR, ".cache", "settings.json")), + SETTINGS_SPREADSHEET_ID, + ttl=float(os.getenv("SETTINGS_CACHE_TTL", "60")), +) def env_bool(name: str, default: bool = False) -> bool: raw = os.getenv(name) @@ -264,38 +276,21 @@ def load_service_account_credentials(scopes): ) # ----- Utility Functions ----- -def read_config(force_refresh=False): - global _CONFIG_ROWS_CACHE, _CONFIG_ROWS_CACHE_TIME +def _load_settings_rows(): + return get_settings_worksheet().get_all_values() + +def read_config(force_refresh=False): config = configparser.ConfigParser(allow_no_value=True) config.optionxform = str - rows = [] - - # 1. 캐시 유효성 판단 (force_refresh 가 아니고, 캐시가 존재하며, TTL 이 지나지 않은 경우) - if not force_refresh and _CONFIG_ROWS_CACHE is not None: - if time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL: - rows = _CONFIG_ROWS_CACHE - - # 2. 캐시가 없거나 만료된 경우 구글 시트에서 직접 새로 로드 - if not rows: - with _CONFIG_LOCK: - # 락 대기 중 다른 스레드가 캐시를 갱신했을 수 있으므로 다시 검사 (Double-Checked Locking) - if not force_refresh and _CONFIG_ROWS_CACHE is not None and time.time() - _CONFIG_ROWS_CACHE_TIME < CONFIG_CACHE_TTL: - rows = _CONFIG_ROWS_CACHE - else: - for _ in range(3): - try: - ws = get_settings_worksheet() - rows = ws.get_all_values() - break - except Exception as e: - time.sleep(1.5) - print(f"Google Sheets 불러오기 재시도 중...: {e}") - - if rows: - _CONFIG_ROWS_CACHE = rows - _CONFIG_ROWS_CACHE_TIME = time.time() + try: + rows = _settings_cache.read(_load_settings_rows, force=force_refresh) + except Exception as exc: + raise HTTPException( + status_code=503, + detail="구글에서 최신 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.", + ) from exc if rows and len(rows) > 1: for row in rows: @@ -320,11 +315,9 @@ def read_config(force_refresh=False): config.set(section, key, val) else: config.set(section, key) - config.set(section, key) return config def write_config(config): - global _CONFIG_ROWS_CACHE, _CONFIG_ROWS_CACHE_TIME rows = [["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]] for section in config.sections(): items = config.items(section) @@ -338,23 +331,35 @@ def write_config(config): v_parts = [p.strip() for p in v.split("|")] rows.append([section, k] + v_parts) - for attempt in range(3): - try: - ws = get_settings_worksheet() - ws.clear() - ws.update(values=rows) - - # 구글 시트에 저장이 성공하면 로컬 캐시도 즉시 최신화 - with _CONFIG_LOCK: - _CONFIG_ROWS_CACHE = rows - _CONFIG_ROWS_CACHE_TIME = time.time() - return - except Exception as e: - print(f"Google Sheets 저장 시도 {attempt+1}/3 실패: {e}") - time.sleep(1.5) - - print("Google Sheets에 설정을 저장하는 데 최종 실패했습니다.") - raise Exception("구글 시트 연동 오류 (할당량 초과). 잠시 후 다시 시도해주세요.") + try: + ws = get_settings_worksheet() + requests = [] + column_count = max(len(row) for row in rows) + if len(rows) > ws.row_count or column_count > ws.col_count: + requests.append({"updateSheetProperties": { + "properties": {"sheetId": ws.id, "gridProperties": { + "rowCount": max(len(rows), ws.row_count), + "columnCount": max(column_count, ws.col_count), + }}, + "fields": "gridProperties(rowCount,columnCount)", + }}) + # One atomic request replaces values and clears old trailing cells. A + # timeout between separate clear/update requests must not erase settings. + requests.append({"updateCells": { + "range": {"sheetId": ws.id}, + "rows": [{"values": [ + {"userEnteredValue": {"stringValue": str(cell)}} for cell in row + ]} for row in rows], + "fields": "userEnteredValue", + }}) + ws.spreadsheet.batch_update({"requests": requests}) + except Exception as exc: + _settings_cache.invalidate() + raise HTTPException( + status_code=503, + detail="설정 저장 응답을 확인하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.", + ) from exc + _settings_cache.publish(rows) # ----- API Endpoints ----- @@ -368,8 +373,8 @@ async def index(request: Request): version_history = [] return templates.TemplateResponse( - request=request, - name="index.html", + request=request, + name="index.html", context={ "version_history": version_history, "root_path": APP_ROOT_PATH, @@ -380,21 +385,17 @@ async def index(request: Request): @app.get("/api/config") async def get_config(): - config = read_config() + if _settings_cache.has_value: + config = read_config() + else: + config = await run_google_io(read_config) data = {} for section in config.sections(): data[section] = dict(config.items(section)) data[section]["__order"] = list(config.options(section)) - return JSONResponse(data) - -@app.post("/api/config/refresh") -async def refresh_config(): - """구글 시트로부터 실시간으로 설정을 동기화하여 캐시를 강제 갱신합니다.""" - try: - read_config(force_refresh=True) - return {"status": "success", "message": "설정 캐시가 성공적으로 갱신되었습니다."} - except Exception as e: - raise HTTPException(status_code=500, detail=f"설정 캐시 갱신 실패: {str(e)}") + return JSONResponse(data, headers={ + "X-Settings-Cache": "stale" if _settings_cache.stale else "fresh", + }) @@ -423,8 +424,10 @@ class SubgroupNamePayload(BaseModel): name: str = "" @app.post("/api/products/settings") -async def save_products_settings(payload: ProductsPayload): - config = read_config() +@google_worker +@settings_update +def save_products_settings(payload: ProductsPayload): + config = read_config(force_refresh=True) if config.has_section("GROUP_NAMES"): config.remove_section("GROUP_NAMES") @@ -461,7 +464,9 @@ async def save_products_settings(payload: ProductsPayload): return {"status": "success"} @app.post("/api/products/subgroup-name") -async def save_product_subgroup_name(payload: SubgroupNamePayload): +@google_worker +@settings_update +def save_product_subgroup_name(payload: SubgroupNamePayload): group_key = payload.group_key.strip() subgroup_index = payload.subgroup_index subgroup_name = payload.name.strip() @@ -471,7 +476,7 @@ async def save_product_subgroup_name(payload: SubgroupNamePayload): if len(subgroup_name) > 40: raise HTTPException(status_code=400, detail="그룹 이름은 40자 이내로 입력해주세요.") - config = read_config() + config = read_config(force_refresh=True) if not config.has_section(group_key): raise HTTPException(status_code=404, detail="상품 분류를 찾을 수 없습니다.") if not config.has_section("SUBGROUP_NAMES"): @@ -526,31 +531,20 @@ def format_phone_number(num_str): -# ----- Google Sheets Global Cache ----- -# ----- Google Sheets Config Cache ----- -_CONFIG_ROWS_CACHE = None -_CONFIG_ROWS_CACHE_TIME = 0.0 -_CONFIG_LOCK = threading.Lock() -CONFIG_CACHE_TTL = 600.0 # 캐시 유효 시간: 10분 - -gs_client_global = None -worksheet_manual_global = None -worksheet_settings_global = None -worksheet_sms_history_global = None -worksheet_manual_history_global = None +# Each Google worker owns its requests session and worksheet handles. +_google_state = threading.local() def get_gspread_client(): - global gs_client_global if gspread is None: raise Exception("gspread 라이브러리가 없습니다.") - if gs_client_global is None: + if getattr(_google_state, "client", None) is None: scopes = ['https://www.googleapis.com/auth/spreadsheets'] creds = load_service_account_credentials(scopes) - gs_client_global = gspread.authorize(creds) - return gs_client_global + _google_state.client = create_google_client(creds) + return _google_state.client def get_manual_worksheet(): - global worksheet_manual_global + worksheet_manual_global = getattr(_google_state, 'manual', None) if worksheet_manual_global is None: client = get_gspread_client() ss = client.open_by_key(MANUAL_SPREADSHEET_ID) @@ -561,10 +555,11 @@ def get_manual_worksheet(): except Exception: pass worksheet_manual_global = ws + _google_state.manual = worksheet_manual_global return worksheet_manual_global def get_settings_worksheet(): - global worksheet_settings_global + worksheet_settings_global = getattr(_google_state, 'settings', None) if worksheet_settings_global is None: client = get_gspread_client() ss = client.open_by_key(SETTINGS_SPREADSHEET_ID) @@ -572,10 +567,11 @@ def get_settings_worksheet(): worksheet_settings_global = ss.worksheet("설정") except gspread.exceptions.WorksheetNotFound: worksheet_settings_global = ss.add_worksheet(title="설정", rows=500, cols=3) + _google_state.settings = worksheet_settings_global return worksheet_settings_global def get_sms_history_worksheet(): - global worksheet_sms_history_global + worksheet_sms_history_global = getattr(_google_state, 'sms_history', None) if worksheet_sms_history_global is None: client = get_gspread_client() ss = client.open_by_key(SETTINGS_SPREADSHEET_ID) @@ -587,10 +583,11 @@ def get_sms_history_worksheet(): worksheet_sms_history_global.add_cols(len(SMS_HISTORY_HEADERS) - worksheet_sms_history_global.col_count) if worksheet_sms_history_global.row_values(1)[:len(SMS_HISTORY_HEADERS)] != SMS_HISTORY_HEADERS: worksheet_sms_history_global.update(values=[SMS_HISTORY_HEADERS], range_name="A1:H1", value_input_option='USER_ENTERED') + _google_state.sms_history = worksheet_sms_history_global return worksheet_sms_history_global def get_manual_history_worksheet(): - global worksheet_manual_history_global + worksheet_manual_history_global = getattr(_google_state, 'manual_history', None) if worksheet_manual_history_global is None: client = get_gspread_client() ss = client.open_by_key(SETTINGS_SPREADSHEET_ID) @@ -599,6 +596,7 @@ def get_manual_history_worksheet(): except gspread.exceptions.WorksheetNotFound: worksheet_manual_history_global = ss.add_worksheet(title="수동발주내역", rows=1000, cols=3) worksheet_manual_history_global.append_row(["일시", "고객명", "주문금액"]) + _google_state.manual_history = worksheet_manual_history_global return worksheet_manual_history_global @app.on_event("startup") @@ -619,18 +617,12 @@ async def startup_event(): if env_bool("SKIP_GOOGLE_INIT", False): print("SKIP_GOOGLE_INIT=1 이므로 구글 시트 선초기화를 건너뜁니다.") else: - try: - print("구글 시트 연동 초기화 중...") - get_manual_worksheet() - get_settings_worksheet() - get_sms_history_worksheet() - get_manual_history_worksheet() - print("구글 시트 연동 완료!") - except Exception as e: - print(f"구글 시트 연동 초기화 실패 (사용 전 권한을 확인하세요): {str(e)}") + # Google unavailability must not delay startup or the DB-backed tabs. + _settings_cache.refresh_in_background(_load_settings_rows) @app.post("/api/order/submit") -async def submit_order_submit(payload: OrderPayload): +@google_worker +def submit_order_submit(payload: OrderPayload): date_str, time_str, current_datetime_str = get_current_time_info() c_tel = format_phone_number(payload.phone) @@ -665,7 +657,26 @@ async def submit_order_submit(payload: OrderPayload): worksheet.append_rows(rows, value_input_option='USER_ENTERED') clipboard_text = "\r\n".join(lines) + "\r\n" - return {"status": "success", "message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.", "clipboard_text": clipboard_text, "timestamp": current_datetime_str} + cs_record_saved_count = 0 + cs_record_warning = "" + if order_status and lines: + try: + korea_tz = datetime.timezone(datetime.timedelta(hours=9)) + record_date = datetime.datetime.now(korea_tz).date() + event_key = f"{uuid.uuid4()}" + cs_record_saved_count = add_special_order_records(record_date, lines, event_key) + except Exception as cs_record_error: + cs_record_warning = "발주 입력은 완료됐지만 CS 기록 자동 저장에 실패했습니다." + print(f"CS 기록 자동 저장 실패: {cs_record_error}") + + return { + "status": "success", + "message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.", + "clipboard_text": clipboard_text, + "timestamp": current_datetime_str, + "cs_record_saved_count": cs_record_saved_count, + "cs_record_warning": cs_record_warning, + } except Exception as e: err_str = str(e) if not err_str or err_str.strip() == "{}": @@ -673,13 +684,14 @@ async def submit_order_submit(payload: OrderPayload): raise HTTPException(status_code=500, detail=f"수동발주 시트 접근 에러 (스프레드시트에 이메일 편집 권한을 추가했는지 확인해주세요!): {err_str}") @app.post("/api/sheet/download_and_clear") -async def download_and_clear_sheet(): +@google_worker +def download_and_clear_sheet(): try: scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'] creds = load_service_account_credentials(scopes) import google.auth.transport.requests - request = google.auth.transport.requests.Request() + request = google.auth.transport.requests.Request(session=GoogleTimeoutSession()) creds.refresh(request) access_token = creds.token @@ -688,7 +700,7 @@ async def download_and_clear_sheet(): url = f"https://docs.google.com/spreadsheets/export?id={MANUAL_SPREADSHEET_ID}&exportFormat=xlsx" req = urllib.request.Request(url, headers={"Authorization": f"Bearer {access_token}"}) - with urllib.request.urlopen(req) as response: + with urllib.request.urlopen(req, timeout=GOOGLE_READ_TIMEOUT) as response: content = response.read() korea_tz = datetime.timezone(datetime.timedelta(hours=9)) @@ -735,7 +747,9 @@ async def download_and_clear_sheet(): @app.get("/api/sms/history") -async def get_history(): +@google_worker +@history_access +def get_history(): local_history = {} def merge_history_item(sheet_item, local_item): if not local_item: @@ -800,7 +814,9 @@ async def get_history(): return [] @app.post("/api/sms/history") -async def add_history(data: dict): +@google_worker +@history_access +def add_history(data: dict): with open(SMS_HISTORY_FILE, 'a', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False) f.write('\n') @@ -839,7 +855,9 @@ async def add_history(data: dict): return {"status": "success"} @app.delete("/api/sms/history") -async def clear_history(): +@google_worker +@history_access +def clear_history(): if os.path.exists(SMS_HISTORY_FILE): os.remove(SMS_HISTORY_FILE) @@ -852,7 +870,9 @@ async def clear_history(): return {"status": "success"} @app.delete("/api/sms/history/{index}") -async def delete_history_item(index: int): +@google_worker +@history_access +def delete_history_item(index: int): try: ws = get_sms_history_worksheet() rows = ws.get_all_values() @@ -887,7 +907,9 @@ async def delete_history_item(index: int): import sys @app.get("/api/manual/history") -async def get_manual_history(): +@google_worker +@history_access +def get_manual_history(): korea_tz = datetime.timezone(datetime.timedelta(hours=9)) today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d") @@ -933,7 +955,9 @@ async def get_manual_history(): return list(local_history.values()) @app.post("/api/manual/history") -async def add_manual_history(data: dict): +@google_worker +@history_access +def add_manual_history(data: dict): local_history = [] korea_tz = datetime.timezone(datetime.timedelta(hours=9)) today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d") @@ -970,7 +994,9 @@ async def add_manual_history(data: dict): return {"status": "success"} @app.delete("/api/manual/history/{timestamp}") -async def delete_manual_history(timestamp: str): +@google_worker +@history_access +def delete_manual_history(timestamp: str): # 구글 시트에서 삭제 try: ws = get_manual_worksheet() @@ -1041,7 +1067,9 @@ async def get_fonts(): return fonts_list @app.post("/api/gift/settings") -async def save_gift_settings(payload: dict): +@google_worker +@settings_update +def save_gift_settings(payload: dict): # 하위 호환성 (기존 rules만 오는 경우) if "rules" in payload: rules = payload["rules"] @@ -1050,7 +1078,7 @@ async def save_gift_settings(payload: dict): rules = payload app_settings = {} - config = read_config() + config = read_config(force_refresh=True) section = "SMS_GIFT_RULES" if section not in config: config.add_section(section) @@ -1075,8 +1103,10 @@ async def save_gift_settings(payload: dict): return {"status": "success"} @app.post("/api/app/settings") -async def save_app_settings(payload: dict): - config = read_config() +@google_worker +@settings_update +def save_app_settings(payload: dict): + config = read_config(force_refresh=True) app_section = "APP_SETTINGS" if app_section not in config: config.add_section(app_section) @@ -1326,8 +1356,8 @@ async def delete_set_item(item_code: str): # ----- 스마트스토어 & 카페24 자동발주 공통 ----- EXCEL_COLUMNS = [ - '주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량', - '주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항', + '주문날짜', '번호', '주문번호', '수령인명', '상품코드', '상품명', '수량', + '주소', '우편번호', '수령인 전화번호', '수령인 휴대폰', '배송시 요구사항', '송장번호', '쇼핑몰명', '비고', '주문번호(쇼핑몰)', '주문목록' ] @@ -1658,7 +1688,7 @@ async def upload_invoices(file: UploadFile = File(...), deliveryCompanyCode: str fail_list.append(f) return { - "status": "success", + "status": "success", "success_count": success_count, "fail_count": len(fail_list), "fails": fail_list, diff --git a/requirements.txt b/requirements.txt index 6b06597..7efb629 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,4 +12,5 @@ bcrypt requests psycopg2-binary python-dotenv -itsdangerous \ No newline at end of file +itsdangerous +holidays diff --git a/routers/coupang_milkrun.py b/routers/coupang_milkrun.py index b6aa4fc..eeba3e2 100644 --- a/routers/coupang_milkrun.py +++ b/routers/coupang_milkrun.py @@ -25,6 +25,7 @@ import requests from fastapi import APIRouter, HTTPException from fastapi.responses import StreamingResponse 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"]) @@ -315,7 +316,7 @@ _sheet_tabs_cache = {} # file_id -> (저장시각, 시트 목록 응답) # 구글이 응답을 안 주면 무한정 매달리지 않도록 (연결 대기, 응답 대기) 초 _HTTP_TIMEOUT = (10, 120) -_HTTP_READ_TIMEOUT = 120 +_HTTP_READ_TIMEOUT = GOOGLE_READ_TIMEOUT # 밀크런 출고리스트 구글 시트 (화면에서 주소를 입력하지 않아도 되도록 기본값으로 둔다) MILKRUN_SHEET_URL = os.getenv( @@ -419,7 +420,7 @@ def _drive_get(session, file_id, params): return session.get( f"https://www.googleapis.com/drive/v3/files/{file_id}", params={**params, "supportsAllDrives": "true"}, - timeout=60, + timeout=GOOGLE_TIMEOUT, ) @@ -463,7 +464,7 @@ def _fetch_drive_workbook_authenticated(file_id): except ImportError: 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"}) if response.status_code != 200: raise HTTPException(status_code=400, detail=_drive_error_detail(response)) @@ -493,7 +494,7 @@ def fetch_drive_file_name(file_id): try: 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"}) if response.status_code == 200: return response.json().get("name", "") @@ -548,7 +549,7 @@ def _read_sheet_tabs(file_id): raise HTTPException(status_code=500, detail="gspread 라이브러리가 설치되어 있지 않습니다.") try: - client = gspread.authorize(_load_credentials([SHEETS_SCOPE])) + client = create_google_client(_load_credentials([SHEETS_SCOPE])) spreadsheet = client.open_by_key(file_id) return { "source": "google_sheet", @@ -672,7 +673,8 @@ def _read_milkrun_sheet(content, sheet_name): @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) if not payload.sheet: @@ -687,7 +689,8 @@ async def get_sheet_rows(payload: SheetRowsRequest): @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) diff --git a/routers/cs_records.py b/routers/cs_records.py new file mode 100644 index 0000000..25df447 --- /dev/null +++ b/routers/cs_records.py @@ -0,0 +1,1438 @@ +import datetime +import io +import os +import threading +from functools import lru_cache +from typing import List, Optional + +import pandas as pd +import psycopg2 +import psycopg2.extras +from fastapi import APIRouter, File, HTTPException, Query, UploadFile +from fastapi.responses import StreamingResponse +from openpyxl import Workbook +from openpyxl.styles import Alignment, Font, PatternFill +from pydantic import BaseModel + +try: + import holidays as holidays_library +except ImportError: # 로컬 의존성 설치 전에도 주말 계산은 동작하도록 한다. + holidays_library = None + + +router = APIRouter(prefix="/api/cs-records", tags=["CS 기록"]) + +DB_CONFIG = { + # 서버(dbx-corm): CS 기록 표는 itemcode_db 에 둔다. CS_RECORD_DB_* 로 따로 지정 가능, 없으면 POSTGRES_* 공통 값. + "host": os.getenv("CS_RECORD_DB_HOST", os.getenv("POSTGRES_HOST", "postgres-db")), + "port": int(os.getenv("CS_RECORD_DB_PORT", os.getenv("POSTGRES_PORT", "5432"))), + "dbname": os.getenv("CS_RECORD_DB_NAME", os.getenv("ITEMCODE_DB", "itemcode_db")), + "user": os.getenv("CS_RECORD_DB_USER", os.getenv("POSTGRES_USER", "king")), + "password": os.getenv("CS_RECORD_DB_PASSWORD", os.getenv("POSTGRES_PASSWORD", "")), +} + +_schema_ready = False +_schema_lock = threading.Lock() + +MEMO_FOLDER_COLORS = { + "#FDE68A", # 노랑 + "#FDA4AF", # 분홍 + "#FDBA74", # 주황 + "#86EFAC", # 초록 + "#93C5FD", # 파랑 + "#C4B5FD", # 보라 + "#CBD5E1", # 회색 +} +DEFAULT_MEMO_FOLDER_COLOR = "#FDE68A" + + +class CSRecordCreate(BaseModel): + record_date: datetime.date + content: str + + +class CSRecordUpdate(BaseModel): + content: Optional[str] = None + is_completed: Optional[bool] = None + + +class CSCopyRequest(BaseModel): + record_date: datetime.date + + +class PermanentMemoCreate(BaseModel): + content: str + folder_id: Optional[int] = None + + +class PermanentMemoUpdate(BaseModel): + content: Optional[str] = None + folder_id: Optional[int] = None + + +class MemoFolderCreate(BaseModel): + name: str + color: str = DEFAULT_MEMO_FOLDER_COLOR + + +class MemoFolderUpdate(BaseModel): + name: Optional[str] = None + color: Optional[str] = None + + +class CSScheduleCreate(BaseModel): + schedule_date: datetime.date + end_date: Optional[datetime.date] = None + title: str + start_time: Optional[datetime.time] = None + end_time: Optional[datetime.time] = None + + +class CSScheduleUpdate(BaseModel): + schedule_date: Optional[datetime.date] = None + end_date: Optional[datetime.date] = None + title: Optional[str] = None + start_time: Optional[datetime.time] = None + end_time: Optional[datetime.time] = None + + +def _connect(): + return psycopg2.connect( + **DB_CONFIG, + cursor_factory=psycopg2.extras.RealDictCursor, + ) + + +def _ensure_schema(): + global _schema_ready + if _schema_ready: + return + + with _schema_lock: + if _schema_ready: + return + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + CREATE TABLE IF NOT EXISTS cs_records ( + id BIGSERIAL PRIMARY KEY, + record_date DATE NOT NULL, + content TEXT NOT NULL, + is_completed BOOLEAN NOT NULL DEFAULT FALSE, + source VARCHAR(30) NOT NULL DEFAULT 'manual', + source_key VARCHAR(255), + copied_from_id BIGINT REFERENCES cs_records(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + """ + ) + cur.execute( + "CREATE INDEX IF NOT EXISTS idx_cs_records_date ON cs_records(record_date, id)" + ) + cur.execute( + """ + CREATE UNIQUE INDEX IF NOT EXISTS ux_cs_records_source_key + ON cs_records(source_key) WHERE source_key IS NOT NULL + """ + ) + cur.execute( + """ + CREATE UNIQUE INDEX IF NOT EXISTS ux_cs_records_copied_item + ON cs_records(record_date, copied_from_id) + WHERE copied_from_id IS NOT NULL + """ + ) + cur.execute( + """ + CREATE TABLE IF NOT EXISTS cs_memo_folders ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(80) NOT NULL UNIQUE, + color VARCHAR(20) NOT NULL DEFAULT '#FDE68A', + is_default BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + """ + ) + cur.execute( + "ALTER TABLE cs_memo_folders ADD COLUMN IF NOT EXISTS color VARCHAR(20) NOT NULL DEFAULT '#FDE68A'" + ) + cur.execute( + """ + INSERT INTO cs_memo_folders (name, is_default) + VALUES ('기본', TRUE) + ON CONFLICT (name) DO UPDATE SET is_default = TRUE + """ + ) + cur.execute( + """ + CREATE UNIQUE INDEX IF NOT EXISTS ux_cs_memo_folders_default + ON cs_memo_folders(is_default) WHERE is_default = TRUE + """ + ) + cur.execute( + """ + CREATE TABLE IF NOT EXISTS cs_permanent_memos ( + id BIGSERIAL PRIMARY KEY, + content TEXT NOT NULL, + folder_id BIGINT REFERENCES cs_memo_folders(id) ON DELETE RESTRICT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + """ + ) + cur.execute( + """ + ALTER TABLE cs_permanent_memos + ADD COLUMN IF NOT EXISTS folder_id BIGINT REFERENCES cs_memo_folders(id) ON DELETE RESTRICT + """ + ) + cur.execute( + """ + UPDATE cs_permanent_memos + SET folder_id = (SELECT id FROM cs_memo_folders WHERE is_default = TRUE LIMIT 1) + WHERE folder_id IS NULL + """ + ) + cur.execute("ALTER TABLE cs_permanent_memos ALTER COLUMN folder_id SET NOT NULL") + cur.execute( + "CREATE INDEX IF NOT EXISTS idx_cs_permanent_memos_folder ON cs_permanent_memos(folder_id, id)" + ) + cur.execute( + """ + CREATE TABLE IF NOT EXISTS cs_schedules ( + id BIGSERIAL PRIMARY KEY, + schedule_date DATE NOT NULL, + end_date DATE NOT NULL, + title VARCHAR(300) NOT NULL, + start_time TIME, + end_time TIME, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + """ + ) + cur.execute("ALTER TABLE cs_schedules ADD COLUMN IF NOT EXISTS end_date DATE") + cur.execute("ALTER TABLE cs_schedules ADD COLUMN IF NOT EXISTS end_time TIME") + cur.execute("UPDATE cs_schedules SET end_date = schedule_date WHERE end_date IS NULL") + cur.execute("ALTER TABLE cs_schedules ALTER COLUMN end_date SET NOT NULL") + cur.execute( + """ + DO $$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conname = 'ck_cs_schedules_date_range' + AND conrelid = 'cs_schedules'::regclass + ) THEN + ALTER TABLE cs_schedules + ADD CONSTRAINT ck_cs_schedules_date_range CHECK (end_date >= schedule_date); + END IF; + END + $$ + """ + ) + cur.execute( + "CREATE INDEX IF NOT EXISTS idx_cs_schedules_date ON cs_schedules(schedule_date, start_time, id)" + ) + conn.commit() + _schema_ready = True + finally: + conn.close() + + +def _service_unavailable(exc: Exception): + print(f"CS 기록 DB 연결 실패: {exc}") + raise HTTPException( + status_code=503, + detail="CS 기록 데이터베이스에 연결할 수 없습니다. 서버 배포 상태 또는 DB 연결 설정을 확인해주세요.", + ) + + +def _clean_content(content: str) -> str: + content = (content or "").strip() + if not content: + raise HTTPException(status_code=400, detail="기록할 내용을 입력해주세요.") + if len(content) > 10000: + raise HTTPException(status_code=400, detail="한 기록은 10,000자까지 입력할 수 있습니다.") + return content + + +def _clean_folder_name(name: str) -> str: + name = (name or "").strip() + if not name: + raise HTTPException(status_code=400, detail="폴더 이름을 입력해주세요.") + if len(name) > 80: + raise HTTPException(status_code=400, detail="폴더 이름은 80자까지 입력할 수 있습니다.") + return name + + +def _clean_folder_color(color: str) -> str: + color = (color or "").strip().upper() + if color not in MEMO_FOLDER_COLORS: + raise HTTPException(status_code=400, detail="선택할 수 없는 폴더 색상입니다.") + return color + + +def _clean_schedule_title(title: str) -> str: + title = (title or "").strip() + if not title: + raise HTTPException(status_code=400, detail="일정 내용을 입력해주세요.") + if len(title) > 300: + raise HTTPException(status_code=400, detail="일정 내용은 300자까지 입력할 수 있습니다.") + return title + + +def _schedule_date_range( + schedule_date: datetime.date, + end_date: Optional[datetime.date], +): + normalized_end = end_date or schedule_date + if normalized_end < schedule_date: + raise HTTPException(status_code=400, detail="종료일은 시작일보다 빠를 수 없습니다.") + if (normalized_end - schedule_date).days > 366: + raise HTTPException(status_code=400, detail="일정 기간은 최대 1년까지 등록할 수 있습니다.") + return schedule_date, normalized_end + + +def _validate_schedule_times( + schedule_date: datetime.date, + end_date: datetime.date, + start_time: Optional[datetime.time], + end_time: Optional[datetime.time], +): + if schedule_date == end_date and start_time is not None and end_time is not None and end_time < start_time: + raise HTTPException(status_code=400, detail="같은 날짜의 종료 시간은 시작 시간보다 빠를 수 없습니다.") + + +def _serialize_record(row): + result = dict(row) + for key in ("record_date", "created_at", "updated_at"): + value = result.get(key) + if value is not None: + result[key] = value.isoformat() + return result + + +def _serialize_permanent_memo(row): + result = dict(row) + for key in ("created_at", "updated_at"): + value = result.get(key) + if value is not None: + result[key] = value.isoformat() + return result + + +def _serialize_schedule(row): + result = dict(row) + for key in ("schedule_date", "end_date"): + if result.get(key) is not None: + result[key] = result[key].isoformat() + for key in ("start_time", "end_time"): + if result.get(key) is not None: + result[key] = result[key].isoformat(timespec="minutes") + for key in ("created_at", "updated_at"): + value = result.get(key) + if value is not None: + result[key] = value.isoformat() + return result + + +@lru_cache(maxsize=16) +def _korean_holidays(year: int): + if holidays_library is None: + return frozenset() + return frozenset(holidays_library.country_holidays("KR", years=[year]).keys()) + + +@lru_cache(maxsize=16) +def _korean_holiday_details(year: int): + if year < 2026 or year > 2030: + return tuple() + details = {} + if holidays_library is not None: + details.update(holidays_library.country_holidays("KR", years=[year], language="ko")) + + # 제헌절은 국경일이므로 사용 중인 holidays 버전과 관계없이 표시한다. + details.setdefault(datetime.date(year, 7, 17), "제헌절") + return tuple(sorted(details.items())) + + +def _extra_holidays(): + values = os.getenv("CS_RECORD_EXTRA_HOLIDAYS", "") + parsed = set() + for value in values.split(","): + value = value.strip() + if not value: + continue + try: + parsed.add(datetime.date.fromisoformat(value)) + except ValueError: + continue + return parsed + + +def next_business_date(record_date: datetime.date) -> datetime.date: + candidate = record_date + datetime.timedelta(days=1) + extra = _extra_holidays() + for _ in range(370): + if ( + candidate.weekday() < 5 + and candidate not in _korean_holidays(candidate.year) + and candidate not in extra + ): + return candidate + candidate += datetime.timedelta(days=1) + raise RuntimeError("다음 영업일을 계산하지 못했습니다.") + + +@router.get("/holidays") +def holiday_calendar(year: int = Query(..., ge=2026, le=2030)): + holidays = [ + {"date": holiday_date.isoformat(), "name": name} + for holiday_date, name in _korean_holiday_details(year) + ] + return {"status": "success", "year": year, "holidays": holidays} + + +@router.get("/memo-folders") +def list_memo_folders(): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + SELECT f.id, f.name, f.color, f.is_default, COUNT(m.id) AS memo_count + FROM cs_memo_folders f + LEFT JOIN cs_permanent_memos m ON m.folder_id = f.id + GROUP BY f.id, f.name, f.color, f.is_default, f.created_at + ORDER BY f.is_default DESC, f.created_at, f.id + """ + ) + folders = [ + { + "id": row["id"], + "name": row["name"], + "color": row["color"], + "is_default": row["is_default"], + "memo_count": int(row["memo_count"]), + } + for row in cur.fetchall() + ] + return {"status": "success", "folders": folders} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.post("/memo-folders") +def create_memo_folder(payload: MemoFolderCreate): + name = _clean_folder_name(payload.name) + color = _clean_folder_color(payload.color) + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + INSERT INTO cs_memo_folders (name, color) + VALUES (%s, %s) + RETURNING id, name, color, is_default + """, + (name, color), + ) + row = cur.fetchone() + conn.commit() + return { + "status": "success", + "folder": {**dict(row), "memo_count": 0}, + } + except psycopg2.IntegrityError: + conn.rollback() + raise HTTPException(status_code=409, detail="같은 이름의 메모 폴더가 이미 있습니다.") + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.patch("/memo-folders/{folder_id}") +def update_memo_folder(folder_id: int, payload: MemoFolderUpdate): + if payload.name is None and payload.color is None: + raise HTTPException(status_code=400, detail="변경할 폴더 설정이 없습니다.") + name = _clean_folder_name(payload.name) if payload.name is not None else None + color = _clean_folder_color(payload.color) if payload.color is not None else None + try: + _ensure_schema() + conn = _connect() + try: + updates = [] + values = [] + if name is not None: + updates.append("name = %s") + values.append(name) + if color is not None: + updates.append("color = %s") + values.append(color) + values.append(folder_id) + with conn.cursor() as cur: + cur.execute( + f""" + UPDATE cs_memo_folders + SET {', '.join(updates)} + WHERE id = %s + RETURNING id, name, color, is_default + """, + values, + ) + row = cur.fetchone() + if row is None: + raise HTTPException(status_code=404, detail="메모 폴더를 찾을 수 없습니다.") + conn.commit() + return {"status": "success", "folder": {**dict(row), "memo_count": 0}} + except psycopg2.IntegrityError: + conn.rollback() + raise HTTPException(status_code=409, detail="같은 이름의 메모 폴더가 이미 있습니다.") + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.delete("/memo-folders/{folder_id}") +def delete_memo_folder(folder_id: int): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + "SELECT id, name, is_default FROM cs_memo_folders WHERE id = %s", + (folder_id,), + ) + folder = cur.fetchone() + if folder is None: + raise HTTPException(status_code=404, detail="메모 폴더를 찾을 수 없습니다.") + if folder["is_default"]: + raise HTTPException(status_code=400, detail="기본 폴더는 삭제할 수 없습니다.") + + cur.execute("SELECT id FROM cs_memo_folders WHERE is_default = TRUE LIMIT 1") + default_folder = cur.fetchone() + cur.execute( + "UPDATE cs_permanent_memos SET folder_id = %s, updated_at = NOW() WHERE folder_id = %s", + (default_folder["id"], folder_id), + ) + moved_count = cur.rowcount + cur.execute("DELETE FROM cs_memo_folders WHERE id = %s", (folder_id,)) + conn.commit() + return { + "status": "success", + "deleted_folder": folder["name"], + "moved_count": moved_count, + "default_folder_id": default_folder["id"], + } + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.get("/permanent") +def list_permanent_memos(folder_id: Optional[int] = Query(None)): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + if folder_id is None: + cur.execute( + """ + SELECT m.id, m.content, m.folder_id, f.name AS folder_name, + m.created_at, m.updated_at + FROM cs_permanent_memos m + JOIN cs_memo_folders f ON f.id = m.folder_id + ORDER BY m.id + """ + ) + else: + cur.execute( + """ + SELECT m.id, m.content, m.folder_id, f.name AS folder_name, + m.created_at, m.updated_at + FROM cs_permanent_memos m + JOIN cs_memo_folders f ON f.id = m.folder_id + WHERE m.folder_id = %s + ORDER BY m.id + """, + (folder_id,), + ) + memos = [_serialize_permanent_memo(row) for row in cur.fetchall()] + return {"status": "success", "memos": memos} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.post("/permanent") +def create_permanent_memo(payload: PermanentMemoCreate): + content = _clean_content(payload.content) + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + folder_id = payload.folder_id + if folder_id is None: + cur.execute("SELECT id FROM cs_memo_folders WHERE is_default = TRUE LIMIT 1") + folder_id = cur.fetchone()["id"] + else: + cur.execute("SELECT id FROM cs_memo_folders WHERE id = %s", (folder_id,)) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="메모 폴더를 찾을 수 없습니다.") + cur.execute( + """ + INSERT INTO cs_permanent_memos (content, folder_id) + VALUES (%s, %s) + RETURNING id, content, folder_id, created_at, updated_at + """, + (content, folder_id), + ) + memo = _serialize_permanent_memo(cur.fetchone()) + conn.commit() + return {"status": "success", "memo": memo} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.patch("/permanent/{memo_id}") +def update_permanent_memo(memo_id: int, payload: PermanentMemoUpdate): + if payload.content is None and payload.folder_id is None: + raise HTTPException(status_code=400, detail="변경할 내용이 없습니다.") + content = _clean_content(payload.content) if payload.content is not None else None + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + updates = [] + values = [] + if content is not None: + updates.append("content = %s") + values.append(content) + if payload.folder_id is not None: + cur.execute("SELECT id FROM cs_memo_folders WHERE id = %s", (payload.folder_id,)) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="메모 폴더를 찾을 수 없습니다.") + updates.append("folder_id = %s") + values.append(payload.folder_id) + updates.append("updated_at = NOW()") + values.append(memo_id) + cur.execute( + f""" + UPDATE cs_permanent_memos + SET {', '.join(updates)} + WHERE id = %s + RETURNING id, content, folder_id, created_at, updated_at + """, + values, + ) + row = cur.fetchone() + if row is None: + raise HTTPException(status_code=404, detail="상시 메모를 찾을 수 없습니다.") + memo = _serialize_permanent_memo(row) + conn.commit() + return {"status": "success", "memo": memo} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.delete("/permanent/{memo_id}") +def delete_permanent_memo(memo_id: int): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM cs_permanent_memos WHERE id = %s RETURNING id", (memo_id,)) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="상시 메모를 찾을 수 없습니다.") + conn.commit() + return {"status": "success"} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.get("/schedules") +def list_schedules( + year: int = Query(..., ge=2000, le=2100), + month: int = Query(..., ge=1, le=12), +): + try: + _ensure_schema() + start = datetime.date(year, month, 1) + end = datetime.date(year + (month == 12), 1 if month == 12 else month + 1, 1) + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + SELECT id, schedule_date, end_date, title, start_time, end_time, created_at, updated_at + FROM cs_schedules + WHERE schedule_date < %s AND end_date >= %s + ORDER BY schedule_date, start_time NULLS FIRST, id + """, + (end, start), + ) + schedules = [_serialize_schedule(row) for row in cur.fetchall()] + return {"status": "success", "year": year, "month": month, "schedules": schedules} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.post("/schedules") +def create_schedule(payload: CSScheduleCreate): + title = _clean_schedule_title(payload.title) + schedule_date, end_date = _schedule_date_range(payload.schedule_date, payload.end_date) + _validate_schedule_times(schedule_date, end_date, payload.start_time, payload.end_time) + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + INSERT INTO cs_schedules (schedule_date, end_date, title, start_time, end_time) + VALUES (%s, %s, %s, %s, %s) + RETURNING id, schedule_date, end_date, title, start_time, end_time, created_at, updated_at + """, + (schedule_date, end_date, title, payload.start_time, payload.end_time), + ) + schedule = _serialize_schedule(cur.fetchone()) + conn.commit() + return {"status": "success", "schedule": schedule} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.patch("/schedules/{schedule_id}") +def update_schedule(schedule_id: int, payload: CSScheduleUpdate): + fields_set = getattr(payload, "model_fields_set", getattr(payload, "__fields_set__", set())) + if not fields_set: + raise HTTPException(status_code=400, detail="변경할 일정 내용이 없습니다.") + + updates = [] + values = [] + if "schedule_date" in fields_set: + if payload.schedule_date is None: + raise HTTPException(status_code=400, detail="일정 날짜를 입력해주세요.") + updates.append("schedule_date = %s") + values.append(payload.schedule_date) + if "end_date" in fields_set: + if payload.end_date is None: + raise HTTPException(status_code=400, detail="일정 종료일을 입력해주세요.") + updates.append("end_date = %s") + values.append(payload.end_date) + if "title" in fields_set: + updates.append("title = %s") + values.append(_clean_schedule_title(payload.title or "")) + if "start_time" in fields_set: + updates.append("start_time = %s") + values.append(payload.start_time) + if "end_time" in fields_set: + updates.append("end_time = %s") + values.append(payload.end_time) + updates.append("updated_at = NOW()") + values.append(schedule_id) + + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + "SELECT schedule_date, end_date, start_time, end_time FROM cs_schedules WHERE id = %s", + (schedule_id,), + ) + current = cur.fetchone() + if current is None: + raise HTTPException(status_code=404, detail="일정을 찾을 수 없습니다.") + candidate_start = payload.schedule_date if "schedule_date" in fields_set else current["schedule_date"] + candidate_end = payload.end_date if "end_date" in fields_set else current["end_date"] + _schedule_date_range(candidate_start, candidate_end) + candidate_start_time = payload.start_time if "start_time" in fields_set else current["start_time"] + candidate_end_time = payload.end_time if "end_time" in fields_set else current["end_time"] + _validate_schedule_times(candidate_start, candidate_end, candidate_start_time, candidate_end_time) + cur.execute( + f""" + UPDATE cs_schedules SET {', '.join(updates)} + WHERE id = %s + RETURNING id, schedule_date, end_date, title, start_time, end_time, created_at, updated_at + """, + values, + ) + row = cur.fetchone() + if row is None: + raise HTTPException(status_code=404, detail="일정을 찾을 수 없습니다.") + schedule = _serialize_schedule(row) + conn.commit() + return {"status": "success", "schedule": schedule} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.delete("/schedules/{schedule_id}") +def delete_schedule(schedule_id: int): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM cs_schedules WHERE id = %s RETURNING id", (schedule_id,)) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="일정을 찾을 수 없습니다.") + conn.commit() + return {"status": "success"} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.get("") +def list_records(record_date: datetime.date = Query(...)): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + SELECT id, record_date, content, is_completed, source, + copied_from_id, created_at, updated_at + FROM cs_records + WHERE record_date = %s + ORDER BY id + """, + (record_date,), + ) + records = [_serialize_record(row) for row in cur.fetchall()] + return {"status": "success", "record_date": record_date.isoformat(), "records": records} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.get("/month") +def month_summary(year: int = Query(..., ge=2000, le=2100), month: int = Query(..., ge=1, le=12)): + try: + _ensure_schema() + start = datetime.date(year, month, 1) + end = datetime.date(year + (month == 12), 1 if month == 12 else month + 1, 1) + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + SELECT record_date, + COUNT(*) AS total_count, + COUNT(*) FILTER (WHERE is_completed) AS completed_count + FROM cs_records + WHERE record_date >= %s AND record_date < %s + GROUP BY record_date + ORDER BY record_date + """, + (start, end), + ) + days = [ + { + "record_date": row["record_date"].isoformat(), + "total_count": int(row["total_count"]), + "completed_count": int(row["completed_count"]), + } + for row in cur.fetchall() + ] + return {"status": "success", "year": year, "month": month, "days": days} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.post("") +def create_record(payload: CSRecordCreate): + content = _clean_content(payload.content) + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + INSERT INTO cs_records (record_date, content) + VALUES (%s, %s) + RETURNING id, record_date, content, is_completed, source, + copied_from_id, created_at, updated_at + """, + (payload.record_date, content), + ) + record = _serialize_record(cur.fetchone()) + conn.commit() + return {"status": "success", "record": record} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.patch("/{record_id}") +def update_record(record_id: int, payload: CSRecordUpdate): + if payload.content is None and payload.is_completed is None: + raise HTTPException(status_code=400, detail="변경할 내용이 없습니다.") + content = _clean_content(payload.content) if payload.content is not None else None + + try: + _ensure_schema() + conn = _connect() + try: + updates = [] + values = [] + if content is not None: + updates.append("content = %s") + values.append(content) + if payload.is_completed is not None: + updates.append("is_completed = %s") + values.append(payload.is_completed) + updates.append("updated_at = NOW()") + values.append(record_id) + with conn.cursor() as cur: + cur.execute( + f""" + UPDATE cs_records SET {', '.join(updates)} + WHERE id = %s + RETURNING id, record_date, content, is_completed, source, + copied_from_id, created_at, updated_at + """, + values, + ) + row = cur.fetchone() + if row is None: + raise HTTPException(status_code=404, detail="기록을 찾을 수 없습니다.") + record = _serialize_record(row) + conn.commit() + return {"status": "success", "record": record} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.delete("/{record_id}") +def delete_record(record_id: int): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM cs_records WHERE id = %s RETURNING id", (record_id,)) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="기록을 찾을 수 없습니다.") + conn.commit() + return {"status": "success"} + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.post("/copy-next") +def copy_to_next_business_day(payload: CSCopyRequest): + try: + _ensure_schema() + target_date = next_business_date(payload.record_date) + conn = _connect() + copied_count = 0 + try: + with conn.cursor() as cur: + cur.execute( + """ + SELECT id, content + FROM cs_records + WHERE record_date = %s AND is_completed = FALSE + ORDER BY id + """, + (payload.record_date,), + ) + for row in cur.fetchall(): + cur.execute( + """ + INSERT INTO cs_records + (record_date, content, is_completed, source, copied_from_id) + VALUES (%s, %s, FALSE, 'copied', %s) + ON CONFLICT DO NOTHING + RETURNING id + """, + (target_date, row["content"], row["id"]), + ) + if cur.fetchone() is not None: + copied_count += 1 + conn.commit() + return { + "status": "success", + "source_date": payload.record_date.isoformat(), + "target_date": target_date.isoformat(), + "copied_count": copied_count, + } + finally: + conn.close() + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +@router.get("/export") +def export_records(): + try: + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + SELECT id, record_date, content, is_completed, source, + created_at, updated_at + FROM cs_records + ORDER BY record_date, id + """ + ) + rows = cur.fetchall() + cur.execute( + """ + SELECT m.id, f.name AS folder_name, f.color AS folder_color, + m.content, m.created_at, m.updated_at + FROM cs_permanent_memos m + JOIN cs_memo_folders f ON f.id = m.folder_id + ORDER BY f.is_default DESC, f.created_at, m.id + """ + ) + permanent_rows = cur.fetchall() + cur.execute( + """ + SELECT id, schedule_date, end_date, title, start_time, end_time, created_at, updated_at + FROM cs_schedules + ORDER BY schedule_date, start_time NULLS FIRST, id + """ + ) + schedule_rows = cur.fetchall() + finally: + conn.close() + + workbook = Workbook() + sheet = workbook.active + sheet.title = "CS 기록" + headers = ["ID", "날짜", "내용", "완료", "출처", "생성일", "수정일"] + sheet.append(headers) + for row in rows: + sheet.append( + [ + row["id"], + row["record_date"].isoformat(), + row["content"], + "완료" if row["is_completed"] else "미완료", + row["source"], + row["created_at"].strftime("%Y-%m-%d %H:%M:%S"), + row["updated_at"].strftime("%Y-%m-%d %H:%M:%S"), + ] + ) + + header_fill = PatternFill("solid", fgColor="2F5597") + for cell in sheet[1]: + cell.fill = header_fill + cell.font = Font(color="FFFFFF", bold=True) + cell.alignment = Alignment(horizontal="center") + sheet.freeze_panes = "A2" + sheet.auto_filter.ref = sheet.dimensions + widths = {"A": 10, "B": 14, "C": 80, "D": 12, "E": 14, "F": 22, "G": 22} + for column, width in widths.items(): + sheet.column_dimensions[column].width = width + for row in sheet.iter_rows(min_row=2): + row[2].alignment = Alignment(wrap_text=True, vertical="top") + + permanent_sheet = workbook.create_sheet("상시 메모") + permanent_sheet.append(["ID", "폴더", "폴더 색상", "내용", "생성일", "수정일"]) + for row in permanent_rows: + permanent_sheet.append( + [ + row["id"], + row["folder_name"], + row["folder_color"], + row["content"], + row["created_at"].strftime("%Y-%m-%d %H:%M:%S"), + row["updated_at"].strftime("%Y-%m-%d %H:%M:%S"), + ] + ) + for cell in permanent_sheet[1]: + cell.fill = header_fill + cell.font = Font(color="FFFFFF", bold=True) + cell.alignment = Alignment(horizontal="center") + permanent_sheet.freeze_panes = "A2" + permanent_sheet.auto_filter.ref = permanent_sheet.dimensions + permanent_sheet.column_dimensions["A"].width = 10 + permanent_sheet.column_dimensions["B"].width = 18 + permanent_sheet.column_dimensions["C"].width = 16 + permanent_sheet.column_dimensions["D"].width = 80 + permanent_sheet.column_dimensions["E"].width = 22 + permanent_sheet.column_dimensions["F"].width = 22 + for row in permanent_sheet.iter_rows(min_row=2): + row[3].alignment = Alignment(wrap_text=True, vertical="top") + + schedule_sheet = workbook.create_sheet("일정") + schedule_sheet.append(["ID", "시작일", "종료일", "시작 시간", "종료 시간", "일정", "생성일", "수정일"]) + for row in schedule_rows: + schedule_sheet.append( + [ + row["id"], + row["schedule_date"].isoformat(), + row["end_date"].isoformat(), + row["start_time"].strftime("%H:%M") if row["start_time"] else "", + row["end_time"].strftime("%H:%M") if row["end_time"] else "", + row["title"], + row["created_at"].strftime("%Y-%m-%d %H:%M:%S"), + row["updated_at"].strftime("%Y-%m-%d %H:%M:%S"), + ] + ) + for cell in schedule_sheet[1]: + cell.fill = header_fill + cell.font = Font(color="FFFFFF", bold=True) + cell.alignment = Alignment(horizontal="center") + schedule_sheet.freeze_panes = "A2" + schedule_sheet.auto_filter.ref = schedule_sheet.dimensions + schedule_sheet.column_dimensions["A"].width = 10 + schedule_sheet.column_dimensions["B"].width = 14 + schedule_sheet.column_dimensions["C"].width = 14 + schedule_sheet.column_dimensions["D"].width = 12 + schedule_sheet.column_dimensions["E"].width = 12 + schedule_sheet.column_dimensions["F"].width = 60 + schedule_sheet.column_dimensions["G"].width = 22 + schedule_sheet.column_dimensions["H"].width = 22 + + output = io.BytesIO() + workbook.save(output) + output.seek(0) + filename = f"cs-records-{datetime.date.today().isoformat()}.xlsx" + return StreamingResponse( + output, + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +def _read_import_file(filename: str, content: bytes): + suffix = os.path.splitext(filename or "")[1].lower() + if suffix in (".xlsx", ".xls"): + sheets = pd.read_excel(io.BytesIO(content), sheet_name=None) + if not sheets: + raise HTTPException(status_code=400, detail="업로드 파일에 시트가 없습니다.") + daily = sheets.get("CS 기록", next(iter(sheets.values()))) + return daily, sheets.get("상시 메모"), sheets.get("일정") + if suffix == ".csv": + for encoding in ("utf-8-sig", "cp949"): + try: + return pd.read_csv(io.BytesIO(content), encoding=encoding), None, None + except UnicodeDecodeError: + continue + raise HTTPException(status_code=400, detail=".xlsx, .xls 또는 .csv 파일만 업로드할 수 있습니다.") + + +def _column(dataframe, *names): + normalized = {str(column).strip().lower(): column for column in dataframe.columns} + for name in names: + if name.lower() in normalized: + return normalized[name.lower()] + return None + + +def _completed_value(value) -> bool: + if pd.isna(value): + return False + if isinstance(value, bool): + return value + return str(value).strip().lower() in {"완료", "true", "1", "y", "yes", "done"} + + +@router.post("/import") +async def import_records(file: UploadFile = File(...)): + raw = await file.read() + if len(raw) > 15 * 1024 * 1024: + raise HTTPException(status_code=400, detail="업로드 파일은 15MB 이하여야 합니다.") + dataframe, permanent_dataframe, schedule_dataframe = _read_import_file(file.filename or "", raw) + date_column = _column(dataframe, "날짜", "record_date", "date") + content_column = _column(dataframe, "내용", "content", "memo") + completed_column = _column(dataframe, "완료", "is_completed", "completed") + source_column = _column(dataframe, "출처", "source") + if date_column is None or content_column is None: + raise HTTPException(status_code=400, detail="파일에 '날짜'와 '내용' 열이 필요합니다.") + + prepared = [] + permanent_prepared = [] + schedule_prepared = [] + skipped = 0 + for _, row in dataframe.iterrows(): + try: + parsed_date = pd.to_datetime(row[date_column], errors="raise").date() + content = str(row[content_column]).strip() + if not content or content.lower() == "nan" or len(content) > 10000: + raise ValueError + completed = _completed_value(row[completed_column]) if completed_column is not None else False + source = str(row[source_column]).strip() if source_column is not None else "import" + if not source or source.lower() == "nan": + source = "import" + prepared.append((parsed_date, content, completed, source[:30])) + except (ValueError, TypeError): + skipped += 1 + + if permanent_dataframe is not None: + permanent_content_column = _column(permanent_dataframe, "내용", "content", "memo") + permanent_folder_column = _column(permanent_dataframe, "폴더", "folder", "folder_name") + permanent_color_column = _column(permanent_dataframe, "폴더 색상", "folder_color", "color") + if permanent_content_column is not None: + for _, row in permanent_dataframe.iterrows(): + content = str(row[permanent_content_column]).strip() + if content and content.lower() != "nan" and len(content) <= 10000: + folder_name = "기본" + folder_color = DEFAULT_MEMO_FOLDER_COLOR + if permanent_folder_column is not None: + imported_folder = str(row[permanent_folder_column]).strip() + if imported_folder and imported_folder.lower() != "nan": + folder_name = imported_folder[:80] + if permanent_color_column is not None: + imported_color = str(row[permanent_color_column]).strip().upper() + if imported_color in MEMO_FOLDER_COLORS: + folder_color = imported_color + permanent_prepared.append((folder_name, folder_color, content)) + else: + skipped += 1 + + if schedule_dataframe is not None: + schedule_date_column = _column(schedule_dataframe, "시작일", "날짜", "schedule_date", "date") + schedule_end_date_column = _column(schedule_dataframe, "종료일", "end_date") + schedule_title_column = _column(schedule_dataframe, "일정", "title", "내용", "content") + schedule_time_column = _column(schedule_dataframe, "시작 시간", "시간", "start_time", "time") + schedule_end_time_column = _column(schedule_dataframe, "종료 시간", "end_time") + if schedule_date_column is not None and schedule_title_column is not None: + for _, row in schedule_dataframe.iterrows(): + try: + schedule_date = pd.to_datetime(row[schedule_date_column], errors="raise").date() + end_date = schedule_date + if schedule_end_date_column is not None and not pd.isna(row[schedule_end_date_column]): + end_date = pd.to_datetime(row[schedule_end_date_column], errors="raise").date() + if end_date < schedule_date or (end_date - schedule_date).days > 366: + raise ValueError + title = str(row[schedule_title_column]).strip() + if not title or title.lower() == "nan" or len(title) > 300: + raise ValueError + start_time = None + end_time = None + if schedule_time_column is not None and not pd.isna(row[schedule_time_column]): + raw_time = row[schedule_time_column] + if isinstance(raw_time, datetime.time): + start_time = raw_time.replace(second=0, microsecond=0) + else: + time_text = str(raw_time).strip() + if time_text and time_text.lower() != "nan": + start_time = datetime.time.fromisoformat(time_text).replace(second=0, microsecond=0) + if schedule_end_time_column is not None and not pd.isna(row[schedule_end_time_column]): + raw_end_time = row[schedule_end_time_column] + if isinstance(raw_end_time, datetime.time): + end_time = raw_end_time.replace(second=0, microsecond=0) + else: + end_time_text = str(raw_end_time).strip() + if end_time_text and end_time_text.lower() != "nan": + end_time = datetime.time.fromisoformat(end_time_text).replace(second=0, microsecond=0) + _validate_schedule_times(schedule_date, end_date, start_time, end_time) + schedule_prepared.append((schedule_date, end_date, title, start_time, end_time)) + except (ValueError, TypeError, HTTPException): + skipped += 1 + + try: + _ensure_schema() + conn = _connect() + added = 0 + permanent_added = 0 + schedule_added = 0 + try: + with conn.cursor() as cur: + for parsed_date, content, completed, source in prepared: + cur.execute( + """ + INSERT INTO cs_records (record_date, content, is_completed, source) + SELECT %s, %s, %s, %s + WHERE NOT EXISTS ( + SELECT 1 FROM cs_records + WHERE record_date = %s AND content = %s + ) + RETURNING id + """, + (parsed_date, content, completed, source, parsed_date, content), + ) + if cur.fetchone() is not None: + added += 1 + else: + skipped += 1 + for folder_name, folder_color, content in permanent_prepared: + cur.execute( + """ + INSERT INTO cs_memo_folders (name, color) + VALUES (%s, %s) + ON CONFLICT (name) DO NOTHING + """, + (folder_name, folder_color), + ) + cur.execute("SELECT id FROM cs_memo_folders WHERE name = %s", (folder_name,)) + folder_id = cur.fetchone()["id"] + cur.execute( + """ + INSERT INTO cs_permanent_memos (content, folder_id) + SELECT %s, %s + WHERE NOT EXISTS ( + SELECT 1 FROM cs_permanent_memos WHERE folder_id = %s AND content = %s + ) + RETURNING id + """, + (content, folder_id, folder_id, content), + ) + if cur.fetchone() is not None: + permanent_added += 1 + else: + skipped += 1 + for schedule_date, end_date, title, start_time, end_time in schedule_prepared: + cur.execute( + """ + INSERT INTO cs_schedules (schedule_date, end_date, title, start_time, end_time) + SELECT %s, %s, %s, %s, %s + WHERE NOT EXISTS ( + SELECT 1 FROM cs_schedules + WHERE schedule_date = %s + AND end_date = %s + AND title = %s + AND start_time IS NOT DISTINCT FROM %s + AND end_time IS NOT DISTINCT FROM %s + ) + RETURNING id + """, + ( + schedule_date, end_date, title, start_time, end_time, + schedule_date, end_date, title, start_time, end_time, + ), + ) + if cur.fetchone() is not None: + schedule_added += 1 + else: + skipped += 1 + conn.commit() + finally: + conn.close() + return { + "status": "success", + "added_count": added, + "permanent_added_count": permanent_added, + "schedule_added_count": schedule_added, + "skipped_count": skipped, + } + except HTTPException: + raise + except Exception as exc: + _service_unavailable(exc) + + +def add_special_order_records( + record_date: datetime.date, + contents: List[str], + event_key: str, +) -> int: + """New CS 특수 발주의 클립보드 문장들을 CS 기록 한 건으로 추가한다.""" + content = "\n".join( + cleaned + for raw_content in contents + if (cleaned := (raw_content or "").strip()) + ) + if not content: + return 0 + + _ensure_schema() + conn = _connect() + try: + with conn.cursor() as cur: + cur.execute( + """ + INSERT INTO cs_records + (record_date, content, is_completed, source, source_key) + VALUES (%s, %s, FALSE, 'new_cs', %s) + ON CONFLICT DO NOTHING + RETURNING id + """, + (record_date, content, f"new-cs:{event_key}"), + ) + added = 1 if cur.fetchone() is not None else 0 + conn.commit() + return added + finally: + conn.close() diff --git a/routers/returns.py b/routers/returns.py index 7c684cf..f0a6275 100644 --- a/routers/returns.py +++ b/routers/returns.py @@ -80,7 +80,7 @@ async def return_lookup(tracking_no: str): """, (tracking_no, tracking_no)) row = cur.fetchone() conn.close() - + if row: return {"success": True, "data": dict(row)} return {"success": False, "message": "송장번호를 찾을 수 없습니다."} @@ -114,14 +114,24 @@ async def create_return_request(req: ReturnRequest): raise HTTPException(status_code=500, detail=str(e)) @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: conn = get_return_db_conn() cur = conn.cursor() - if tracking_no: - cur.execute("SELECT * FROM return_requests WHERE TRIM(tracking_no) = %s ORDER BY created_at DESC LIMIT 1", (tracking_no.strip(),)) - else: - cur.execute("SELECT * FROM return_requests ORDER BY id DESC LIMIT 50") + conditions, params = [], [] + if tracking_no and tracking_no.strip(): + conditions.append("regexp_replace(r.tracking_no, '[-[:space:]]', '', 'g') = %s") + 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() conn.close() return {"success": True, "data": [dict(r) for r in rows]} @@ -133,25 +143,25 @@ async def create_return_receive_bulk(req: BulkReturnReceive): try: from datetime import datetime today = datetime.now().strftime("%Y-%m-%d") - + conn_return = get_return_db_conn() cur_return = conn_return.cursor() - + conn_order = get_order_db_conn() cur_order = conn_order.cursor() - + success_count = 0 - + for tracking_no in req.tracking_numbers: tracking_no = tracking_no.strip() if not tracking_no: continue - + mall = "" receiver_name = "" phone = "" address = "" - + # 1. Check return_requests cur_return.execute("SELECT mall, receiver_name, phone, address, request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (tracking_no,)) req_row = cur_return.fetchone() @@ -184,7 +194,7 @@ async def create_return_receive_bulk(req: BulkReturnReceive): receiver_name = ord_row['recipient_name'] or "" phone = ord_row['recipient_phone'] or ord_row['recipient_mobile'] or "" address = ord_row['address'] or "" - + # Insert into return_receivings cur_return.execute(""" 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) """, (today, tracking_no, mall, receiver_name, phone, address, remarks, "환불 대기")) success_count += 1 - + conn_return.commit() conn_return.close() conn_order.close() - + return {"success": True, "count": success_count} except Exception as 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() conn = get_return_db_conn() cur = conn.cursor() - + # 중복 송장 검사 if req.id: cur.execute(""" @@ -222,7 +232,7 @@ async def create_return_receive(req: ReturnReceive): FROM return_receivings WHERE TRIM(tracking_no) = %s """, (req.tracking_no,)) - + dup = cur.fetchone() if dup: conn.close() @@ -231,7 +241,7 @@ async def create_return_receive(req: ReturnReceive): "error_type": "duplicate", "data": dict(dup) } - + if not req.id: cur.execute("SELECT request_type, remarks FROM return_requests WHERE TRIM(tracking_no) = %s", (req.tracking_no,)) req_row = cur.fetchone() @@ -271,11 +281,18 @@ async def create_return_receive(req: ReturnReceive): raise HTTPException(status_code=500, detail=str(e)) @router.get("/receive") -async def get_return_receives(): +async def get_return_receives(tracking_no: Optional[str] = None, all_records: bool = False): try: conn = get_return_db_conn() 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() conn.close() return {"success": True, "data": [dict(r) for r in rows]} diff --git a/static/css/cs_records.css b/static/css/cs_records.css new file mode 100644 index 0000000..ee40163 --- /dev/null +++ b/static/css/cs_records.css @@ -0,0 +1,1601 @@ +.cs-record-tab { + min-height: 0; + color: #1f2937; +} + +.cs-record-tab.active { + display: block; + overflow: auto; +} + +.cs-record-layout { + display: grid; + grid-template-columns: 270px 600px minmax(0, 1fr); + gap: 12px; + height: 100%; + min-height: 0; + min-width: 0; +} + +.cs-calendar-card, +.cs-record-card, +.cs-permanent-card { + background: rgba(255, 255, 255, 0.96); + border: 1px solid rgba(203, 213, 224, 0.9); + border-radius: 14px; + box-shadow: 0 12px 30px rgba(15, 23, 42, 0.14); +} + +.cs-calendar-card { + display: flex; + align-self: stretch; + width: 270px; + min-height: 0; + flex-direction: column; + padding: 12px; +} + +.cs-calendar-header { + display: grid; + grid-template-columns: 30px 1fr 30px; + align-items: center; + gap: 8px; + margin-bottom: 10px; +} + +.cs-calendar-header h2 { + margin: 0; + color: #1e293b; + font-size: 0.92rem; + text-align: center; +} + +.cs-icon-button { + width: 30px; + height: 30px; + border: 1px solid #dbe3ed; + border-radius: 9px; + background: #f8fafc; + color: #334155; + font-size: 1.3rem; + line-height: 1; + cursor: pointer; +} + +.cs-icon-button:hover { + background: #e8f1fb; + color: #2563eb; +} + +.cs-calendar-weekdays, +.cs-calendar-grid { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + gap: 4px; +} + +.cs-calendar-weekdays { + margin-bottom: 5px; + color: #64748b; + font-size: 0.86rem; + font-weight: 800; + text-align: center; +} + +.cs-calendar-weekdays span:first-child, +.cs-calendar-day.sunday { + color: #dc2626; +} + +.cs-calendar-weekdays span:last-child, +.cs-calendar-day.saturday { + color: #2563eb; +} + +.cs-calendar-blank, +.cs-calendar-day { + aspect-ratio: 1; + min-width: 0; +} + +.cs-calendar-day { + position: relative; + display: grid; + place-items: center; + border: 1px solid transparent; + border-radius: 9px; + background: transparent; + color: #334155; + font-size: 0.86rem; + cursor: pointer; +} + +.cs-calendar-day:hover { + background: #eff6ff; + border-color: #bfdbfe; +} + +.cs-calendar-day.today { + border-color: #94a3b8; + font-weight: 700; +} + +.cs-calendar-day.selected { + background: #2563eb; + border-color: #2563eb; + color: #fff; + font-weight: 700; +} + +.cs-calendar-day.holiday:not(.selected) { + background: #fff1f2; + color: #dc2626; + font-weight: 800; +} + +.cs-calendar-day.has-record::after { + content: ""; + position: absolute; + bottom: 4px; + width: 5px; + height: 5px; + border-radius: 50%; + background: #10b981; +} + +.cs-calendar-day.has-incomplete::after { + background: #f97316; +} + +.cs-calendar-day.selected::after { + background: #fff; +} + +.cs-calendar-schedule-marker { + position: absolute; + top: 3px; + right: 3px; + width: 6px; + height: 6px; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 50%; + background: #7c3aed; + box-shadow: 0 1px 2px rgba(76, 29, 149, 0.3); +} + +.cs-calendar-day.selected .cs-calendar-schedule-marker { + background: #f5d0fe; + border-color: #fff; +} + +.cs-calendar-legend { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin-top: 19px; + color: #64748b; + font-size: 0.65rem; +} + +.cs-calendar-legend span { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.cs-legend-dot { + width: 7px; + height: 7px; + border-radius: 50%; +} + +.cs-legend-dot.has-record { + background: #10b981; +} + +.cs-legend-dot.incomplete { + background: #f97316; +} + +.cs-legend-dot.holiday { + background: #dc2626; +} + +.cs-legend-dot.schedule { + background: #7c3aed; +} + +.cs-schedule-panel { + display: flex; + min-height: 0; + flex: 1; + flex-direction: column; + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #e2e8f0; +} + +.cs-schedule-primary-actions { + display: grid; + grid-template-columns: minmax(0, 1fr) 40px; + gap: 7px; +} + +.cs-schedule-add-button { + display: flex; + align-items: center; + justify-content: center; + gap: 5px; + width: 100%; + padding: 10px 12px; + border: 0; + border-radius: 9px; + background: linear-gradient(135deg, #6d28d9, #7c3aed); + box-shadow: 0 5px 12px rgba(109, 40, 217, 0.2); + color: #fff; + font-size: 0.82rem; + font-weight: 800; + cursor: pointer; +} + +.cs-schedule-add-button span { + font-size: 1rem; + line-height: 1; +} + +.cs-schedule-settings-button { + display: grid; + width: 40px; + min-width: 40px; + place-items: center; + padding: 0; + border: 0; + background: transparent; + box-shadow: none; + color: #475569; + font-size: 1.5rem; + line-height: 1; + cursor: pointer; +} + +.cs-schedule-settings-button:hover { + transform: scale(1.08); +} + +.cs-schedule-add-button:hover { + background: linear-gradient(135deg, #5b21b6, #6d28d9); + transform: translateY(-1px); +} + +.cs-schedule-list-header { + display: flex; + align-items: center; + justify-content: space-between; + margin: 13px 2px 7px; +} + +.cs-schedule-list-header h3 { + margin: 0; + color: #1e293b; + font-size: 0.76rem; +} + +.cs-schedule-list-header span { + padding: 2px 7px; + border-radius: 999px; + background: #f1f5f9; + color: #64748b; + font-size: 0.62rem; + font-weight: 700; +} + +.cs-schedule-list { + min-height: 0; + flex: 1; + overflow-y: auto; + padding-right: 2px; + scrollbar-width: thin; + scrollbar-color: #c4b5fd transparent; +} + +.cs-schedule-empty { + display: flex; + align-items: center; + flex-direction: column; + padding: 18px 8px; + border: 1px dashed #d8b4fe; + border-radius: 9px; + background: #faf5ff; + color: #64748b; + text-align: center; +} + +.cs-schedule-empty > span { + margin-bottom: 4px; + font-size: 1.2rem; +} + +.cs-schedule-empty strong { + color: #475569; + font-size: 0.7rem; +} + +.cs-schedule-empty small { + margin-top: 3px; + font-size: 0.58rem; +} + +.cs-schedule-day { + margin-bottom: 8px; + overflow: hidden; + border: 1px solid #e2e8f0; + border-radius: 9px; + background: #fff; +} + +.cs-schedule-day.selected { + border-color: #c4b5fd; + box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.09); +} + +.cs-schedule-day-heading { + display: flex; + align-items: center; + width: 100%; + padding: 7px 8px; + border: 0; + border-bottom: 1px solid #f1f5f9; + background: #f8fafc; + color: #334155; + text-align: left; + cursor: pointer; +} + +.cs-schedule-day.selected .cs-schedule-day-heading { + background: #f5f3ff; +} + +.cs-schedule-date-number { + display: grid; + flex: 0 0 auto; + width: 29px; + height: 29px; + place-items: center; + border-radius: 8px; + background: #ede9fe; + color: #6d28d9; + font-size: 0.82rem; + font-weight: 900; +} + +.cs-schedule-date-details { + display: flex; + min-width: 0; + flex-direction: column; + margin-left: 8px; +} + +.cs-schedule-date-details strong { + color: #334155; + font-size: 0.66rem; +} + +.cs-schedule-date-details small { + margin-top: 1px; + color: #94a3b8; + font-size: 0.56rem; +} + +.cs-schedule-today-badge { + margin-left: auto; + padding: 2px 6px; + border-radius: 999px; + background: #7c3aed; + color: #fff; + font-size: 0.55rem; + font-weight: 800; +} + +.cs-schedule-item { + display: grid; + grid-template-columns: 34px 6px minmax(0, 1fr) auto; + align-items: center; + gap: 5px; + min-height: 32px; + padding: 4px 6px; +} + +.cs-schedule-item + .cs-schedule-item { + border-top: 1px solid #f1f5f9; +} + +.cs-schedule-item:hover { + background: #fcfaff; +} + +.cs-schedule-time { + color: #475569; + font-size: 0.6rem; + font-variant-numeric: tabular-nums; + text-align: right; +} + +.cs-schedule-time.all-day { + color: #7c3aed; + font-weight: 800; +} + +.cs-schedule-list-marker { + width: 5px; + height: 18px; + border-radius: 999px; + background: #8b5cf6; +} + +.cs-schedule-title-button { + overflow: hidden; + padding: 4px 2px; + border: 0; + background: transparent; + color: #1e293b; + font-size: 0.76rem; + line-height: 1.35; + text-align: left; + white-space: normal; + word-break: break-word; + cursor: pointer; +} + +.cs-schedule-title-button:hover { + color: #6d28d9; +} + +.cs-schedule-item-actions { + display: flex; + gap: 1px; + opacity: 0; + transition: opacity 0.12s ease; +} + +.cs-schedule-item:hover .cs-schedule-item-actions, +.cs-schedule-item:focus-within .cs-schedule-item-actions, +.cs-schedule-row:hover .cs-schedule-item-actions, +.cs-schedule-row:focus-within .cs-schedule-item-actions { + opacity: 1; +} + +.cs-schedule-item-actions button { + display: grid; + width: 22px; + height: 22px; + padding: 3px; + place-items: center; + border: 0; + border-radius: 5px; + background: transparent; + color: #64748b; + cursor: pointer; +} + +.cs-schedule-item-actions button:hover { + background: #f1f5f9; +} + +.cs-schedule-item-actions button svg { + width: 16px; + height: 16px; + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; +} + +.cs-schedule-item-actions button:last-child { + color: #dc2626; +} + +.cs-schedule-row { + display: grid; + grid-template-columns: 62px minmax(0, 1fr) 24px; + align-items: stretch; + gap: 8px; + margin-bottom: 7px; + padding: 7px; + border: 1px solid #e2e8f0; + border-radius: 10px; + background: #fff; + transition: border-color 0.12s ease, box-shadow 0.12s ease; +} + +.cs-schedule-row:hover { + border-color: #c4b5fd; + box-shadow: 0 3px 10px rgba(109, 40, 217, 0.1); +} + +.cs-schedule-row.selected { + border-color: #a78bfa; + background: #fdfcff; + box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.08); +} + +.cs-schedule-date-card { + display: flex; + min-height: 58px; + align-items: center; + justify-content: center; + flex-direction: column; + padding: 4px; + border: 1px solid #ddd6fe; + border-radius: 8px; + background: linear-gradient(145deg, #faf5ff, #ede9fe); + color: #6d28d9; + line-height: 1.05; + cursor: pointer; +} + +.cs-schedule-date-card:hover { + border-color: #a78bfa; + background: #ede9fe; +} + +.cs-schedule-card-day { + display: flex; + max-width: 100%; + align-items: center; + justify-content: center; + gap: 1px; + font-size: 1.15rem; + font-weight: 900; + letter-spacing: -0.04em; + line-height: 1; + text-align: center; +} + +.cs-schedule-card-weekday { + display: flex; + align-items: center; + justify-content: center; + gap: 1px; + margin-top: 6px; + font-size: 0.72rem; + font-weight: 800; + line-height: 1; +} + +.cs-schedule-card-day b, +.cs-schedule-card-weekday b { + color: #111827; + font: inherit; +} + +.cs-schedule-card-day i, +.cs-schedule-card-weekday i { + color: #94a3b8; + font: inherit; + font-style: normal; +} + +.cs-schedule-date-card .saturday { + color: #2563eb; +} + +.cs-schedule-date-card .holiday { + color: #dc2626; +} + +.cs-schedule-date-card .weekday { + color: #111827; +} + +.cs-schedule-date-card strong { + max-width: 100%; + color: inherit; +} + +.cs-schedule-date-card span { + color: inherit; +} + +.cs-schedule-row-content { + display: grid; + min-width: 0; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto minmax(24px, auto); + align-content: center; + column-gap: 3px; +} + +.cs-schedule-row-top { + display: flex; + align-items: center; + gap: 5px; + grid-column: 1; + grid-row: 1; +} + +.cs-schedule-row-content .cs-schedule-title-button { + grid-column: 1; + grid-row: 2; +} + +.cs-schedule-row > .cs-schedule-item-actions { + display: flex; + align-self: stretch; + align-items: center; + justify-content: space-between; + flex-direction: column; + opacity: 0; +} + +.cs-data-actions { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #e2e8f0; +} + +.cs-secondary-button, +.cs-primary-button, +.cs-copy-button { + border: 0; + border-radius: 8px; + font-weight: 700; + text-align: center; + cursor: pointer; + transition: background 0.15s ease, transform 0.15s ease; +} + +.cs-secondary-button { + padding: 9px 7px; + border: 1px solid #cbd5e1; + background: #f8fafc; + color: #334155; + font-size: 0.76rem; + text-decoration: none; +} + +.cs-secondary-button:hover { + background: #eef2f7; +} + +.cs-upload-help { + margin-top: 8px; + color: #64748b; + font-size: 0.62rem; + line-height: 1.45; +} + +.cs-record-card { + width: 600px; + display: flex; + flex-direction: column; + min-height: 0; + overflow: hidden; +} + +.cs-record-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 14px 16px 11px; + border-bottom: 1px solid #e2e8f0; +} + +.cs-record-header h1 { + margin: 3px 0 2px; + color: #0f172a; + font-size: 1.25rem; +} + +.cs-record-header p { + color: #64748b; + font-size: 0.7rem; +} + +.cs-eyebrow { + color: #2563eb; + font-size: 0.64rem; + font-weight: 800; + letter-spacing: 0.05em; +} + +.cs-copy-button { + flex: 0 0 auto; + padding: 10px 14px; + background: #e8f1ff; + color: #1d4ed8; + font-size: 0.8rem; +} + +.cs-copy-button:hover { + background: #dbeafe; +} + +.cs-record-actions { + display: flex; + align-items: center; + gap: 7px; +} + +.cs-copy-selected-button { + flex: 0 0 auto; + padding: 10px 12px; + border: 0; + border-radius: 8px; + background: #334155; + color: #fff; + font-size: 0.78rem; + font-weight: 700; + cursor: pointer; +} + +.cs-copy-selected-button:hover { + background: #1e293b; +} + +.cs-copy-button:disabled, +.cs-primary-button:disabled { + cursor: wait; + opacity: 0.55; +} + +.cs-record-status { + position: fixed; + top: 50%; + left: 50%; + z-index: 12000; + min-width: 260px; + max-width: min(520px, calc(100vw - 30px)); + padding: 12px 18px; + border: 1px solid #fed7aa; + border-radius: 10px; + background: #fff7ed; + box-shadow: 0 12px 32px rgba(15, 23, 42, 0.28); + color: #9a3412; + font-size: 0.75rem; + font-weight: 700; + text-align: center; + transform: translate(-50%, calc(-50% - 12px)); + opacity: 0; + transition: opacity 0.15s ease, transform 0.15s ease; + pointer-events: none; +} + +.cs-record-status.visible { + transform: translate(-50%, -50%); + opacity: 1; +} + +.cs-record-status.success { + background: #ecfdf5; + border-color: #a7f3d0; + color: #047857; +} + +.cs-permanent-card { + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + overflow: hidden; +} + +.cs-permanent-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 18px 16px 14px; + border-bottom: 1px solid #e2e8f0; +} + +.cs-permanent-header h2 { + margin: 4px 0; + color: #0f172a; + font-size: 1rem; +} + +.cs-permanent-header p { + color: #64748b; + font-size: 0.66rem; + line-height: 1.45; +} + +.cs-permanent-composer { + display: flex; + flex-direction: column; + gap: 8px; + margin: 14px; +} + +.cs-permanent-composer textarea { + width: 100%; + min-height: 88px; + resize: vertical; + padding: 10px; + border: 1px solid #cbd5e1; + border-radius: 9px; + background: #f8fafc; + color: #1e293b; + font-size: 0.75rem; + line-height: 1.5; + outline: none; +} + +.cs-permanent-composer textarea:focus { + border-color: #60a5fa; + box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.16); +} + +.cs-permanent-list { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 0 14px 14px; +} + +.cs-permanent-item { + position: relative; + margin-bottom: 9px; + padding: 8px 27px 8px 8px; + border: 1px solid #fde68a; + border-radius: 9px; + background: #fffbeb; +} + +.cs-permanent-text { + width: 100%; + min-height: 34px; + resize: none; + overflow: hidden; + border: 0; + background: transparent; + color: #3f3a2e; + caret-color: #0f172a; + cursor: text; + font-size: 0.73rem; + line-height: 1.5; + outline: none; +} + +.cs-permanent-text:focus { + border-radius: 4px; + background: rgba(255, 255, 255, 0.38); + box-shadow: inset 0 0 0 1px rgba(51, 65, 85, 0.2); +} + +.cs-permanent-icon-button { + position: absolute; + top: 7px; + display: grid; + width: 25px; + height: 25px; + padding: 4px; + place-items: center; + border: 0; + border-radius: 5px; + background: transparent; + color: #a16207; + cursor: pointer; +} + +.cs-permanent-icon-button svg { + width: 17px; + height: 17px; + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; +} + +.cs-permanent-copy { + left: 7px; +} + +.cs-permanent-delete { + right: 7px; +} + +.cs-permanent-icon-button:hover { + background: rgba(255, 255, 255, 0.45); +} + +.cs-permanent-copy:hover { + color: #2563eb; +} + +.cs-permanent-delete:hover { + color: #dc2626; +} + +.cs-add-memo-button { + flex: 0 0 auto; + min-width: 112px; + padding: 12px 15px; + border: 0; + border-radius: 9px; + background: #2563eb; + color: #fff; + font-size: 0.86rem; + font-weight: 800; + cursor: pointer; +} + +.cs-add-memo-button:hover { + background: #1d4ed8; +} + +.cs-folder-toolbar { + display: flex; + align-items: flex-end; + gap: 8px; + padding: 10px 12px 0; + border-bottom: 1px solid #dbe3ed; +} + +.cs-folder-tabs { + display: flex; + flex: 1; + min-width: 0; + gap: 3px; + overflow-x: auto; +} + +.cs-folder-tab { + flex: 0 0 auto; + padding: 7px 10px; + border: 1px solid #cbd5e1; + border-bottom: 0; + border-radius: 7px 7px 0 0; + background: color-mix(in srgb, var(--folder-color, #cbd5e1) 28%, white); + color: #475569; + font-size: 0.74rem; + cursor: pointer; +} + +.cs-folder-tab.active { + background: color-mix(in srgb, var(--folder-color, #fde68a) 72%, white); + color: #334155; + font-weight: 800; + box-shadow: inset 0 3px 0 var(--folder-color, #f59e0b); +} + +.cs-folder-count { + margin-left: 4px; + color: #94a3b8; + font-size: 0.58rem; +} + +.cs-folder-actions { + display: flex; + flex: 0 0 auto; + gap: 4px; + padding-bottom: 3px; +} + +.cs-folder-actions button { + padding: 5px 7px; + border: 1px solid #cbd5e1; + border-radius: 6px; + background: #fff; + color: #475569; + font-size: 0.68rem; + cursor: pointer; +} + +.cs-folder-actions button:last-child { + color: #b91c1c; +} + +.cs-permanent-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-content: start; + gap: 8px; + padding: 12px; +} + +.cs-permanent-column { + display: flex; + min-width: 0; + flex-direction: column; + gap: 8px; + align-self: start; +} + +.cs-permanent-list > .cs-empty-state { + grid-column: 1 / -1; +} + +.cs-permanent-item { + min-height: 112px; + margin: 0; + padding: 34px 12px 12px; + border: 1px solid color-mix(in srgb, var(--memo-color, #fde68a) 78%, #8a6500); + border-radius: 4px; + background: linear-gradient( + 145deg, + color-mix(in srgb, var(--memo-color, #fde68a) 66%, white) 0%, + var(--memo-color, #fde68a) 100% + ); + box-shadow: 2px 4px 9px rgba(120, 89, 0, 0.16); + transform: rotate(-0.2deg); +} + +.cs-permanent-item:nth-child(even) { + transform: rotate(0.2deg); +} + +.cs-permanent-text { + min-height: 80px; + font-size: 0.8rem; + line-height: 1.45; +} + +.cs-modal { + position: fixed; + inset: 0; + z-index: 13000; + display: grid; + place-items: center; + padding: 20px; + background: rgba(15, 23, 42, 0.5); +} + +.cs-modal[hidden] { + display: none; +} + +.cs-modal-dialog { + width: min(520px, calc(100vw - 32px)); + padding: 22px; + border: 1px solid #dbe3ed; + border-radius: 14px; + background: #fff; + box-shadow: 0 22px 65px rgba(15, 23, 42, 0.35); +} + +.cs-modal-dialog-small { + width: min(390px, calc(100vw - 32px)); +} + +.cs-modal-dialog h3 { + display: block; + margin: 0 0 16px; + border: 0; + color: #0f172a; + font-size: 1.05rem; +} + +.cs-schedule-modal-heading { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 12px; +} + +.cs-schedule-modal-heading h3 { + margin: 2px 0 0; +} + +.cs-schedule-modal-icon { + display: grid; + width: 40px; + height: 40px; + place-items: center; + border-radius: 11px; + background: #ede9fe; + font-size: 1.2rem; +} + +.cs-schedule-form-row { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.cs-schedule-date-row { + grid-template-columns: repeat(2, minmax(0, 1fr)) auto; + align-items: end; +} + +.cs-all-day-toggle { + display: inline-flex !important; + min-height: 40px; + margin: 0 0 1px !important; + align-items: center; + gap: 6px; + color: #334155 !important; + font-size: 0.74rem !important; + font-weight: 700 !important; + white-space: nowrap; + cursor: pointer; +} + +.cs-all-day-toggle input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +.cs-all-day-toggle span { + display: grid; + width: 19px; + height: 19px; + box-sizing: border-box; + place-items: center; + border: 1.5px solid #94a3b8; + border-radius: 5px; + background: #fff; + color: #fff; + transition: background-color 0.15s ease, border-color 0.15s ease; +} + +.cs-all-day-toggle input:checked + span { + border-color: #2563eb; + background: #2563eb; +} + +.cs-all-day-toggle input:checked + span::after { + content: '✓'; + font-size: 0.78rem; + font-weight: 900; + line-height: 1; +} + +.cs-all-day-toggle input:focus-visible + span { + outline: 3px solid rgba(37, 99, 235, 0.2); + outline-offset: 2px; +} + +.cs-schedule-time-row { + margin-top: 2px; +} + +.cs-time-select-group { + display: grid; + grid-template-columns: 1.15fr 0.8fr 0.8fr; + gap: 4px; +} + +.cs-modal-dialog .cs-time-select-group select { + min-width: 0; + padding: 10px 3px; + text-align: center; + text-align-last: center; +} + +.cs-schedule-time-row.is-all-day { + opacity: 0.48; +} + +.cs-schedule-time-row.is-all-day select { + cursor: not-allowed; +} + +.cs-data-modal-description { + margin: 0; + color: #475569; + font-size: 0.74rem; + line-height: 1.55; +} + +.cs-data-modal .cs-data-actions { + margin-top: 16px; + padding-top: 0; + border-top: 0; +} + +.cs-data-modal .cs-secondary-button { + display: flex; + box-sizing: border-box; + width: 100%; + height: 54px; + margin: 0; + align-items: center; + justify-content: center; + padding: 11px 8px; + font-size: 0.82rem; + line-height: 1.2; +} + +.cs-data-modal .cs-upload-help { + margin-bottom: 0; + font-size: 0.68rem; +} + +#cs-schedule-title, +#cs-memo-content { + font-size: 0.86rem; +} + +.cs-optional-label { + margin-left: 3px; + color: #94a3b8; + font-size: 0.6rem; + font-weight: 500; +} + +.cs-modal-dialog label { + display: block; + margin: 10px 0 5px; + color: #475569; + font-size: 0.7rem; + font-weight: 700; +} + +.cs-modal-dialog input, +.cs-modal-dialog select, +.cs-modal-dialog textarea { + width: 100%; + padding: 10px 11px; + border: 1px solid #cbd5e1; + border-radius: 8px; + background: #fff; + color: #1e293b; + font-size: 0.78rem; + outline: none; +} + +.cs-modal-dialog textarea { + resize: vertical; + line-height: 1.5; +} + +.cs-modal-dialog input:focus, +.cs-modal-dialog select:focus, +.cs-modal-dialog textarea:focus { + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.13); +} + +.cs-modal-help { + margin-top: 10px; + color: #64748b; + font-size: 0.66rem; + line-height: 1.5; +} + +.cs-color-fieldset { + margin: 14px 0 0; + padding: 0; + border: 0; +} + +.cs-color-fieldset legend { + margin-bottom: 7px; + color: #475569; + font-size: 0.7rem; + font-weight: 700; +} + +.cs-color-palette { + display: grid; + grid-template-columns: repeat(7, 36px); + gap: 8px; +} + +.cs-color-choice { + position: relative; + display: block; + width: 36px; + height: 36px; + cursor: pointer; +} + +.cs-color-choice input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +.cs-color-swatch { + display: block; + width: 36px; + height: 36px; + border: 2px solid rgba(71, 85, 105, 0.22); + border-radius: 50%; + background: var(--swatch-color); + box-shadow: 0 2px 5px rgba(15, 23, 42, 0.13); + transition: transform 0.12s ease, box-shadow 0.12s ease; +} + +.cs-color-choice input:checked + .cs-color-swatch { + border-color: #1d4ed8; + box-shadow: 0 0 0 3px #dbeafe, 0 2px 5px rgba(15, 23, 42, 0.16); + transform: scale(1.08); +} + +.cs-color-choice input:focus-visible + .cs-color-swatch { + outline: 2px solid #2563eb; + outline-offset: 3px; +} + +.cs-delete-message { + margin: 0 0 10px; + color: #334155; + font-size: 0.78rem; +} + +.cs-memo-delete-preview { + max-height: 150px; + overflow-y: auto; + padding: 12px; + border: 1px solid color-mix(in srgb, var(--memo-color, #fde68a) 78%, #8a6500); + border-radius: 7px; + background: color-mix(in srgb, var(--memo-color, #fde68a) 58%, white); + color: #4b5563; + font-size: 0.72rem; + line-height: 1.5; + white-space: pre-wrap; + word-break: break-word; +} + +.cs-schedule-delete-preview { + display: flex; + flex-direction: column; + gap: 5px; + padding: 12px; + border: 1px solid #ddd6fe; + border-radius: 8px; + background: #f5f3ff; +} + +.cs-schedule-delete-preview strong { + color: #6d28d9; + font-size: 0.7rem; +} + +.cs-schedule-delete-preview span { + color: #334155; + font-size: 0.78rem; + line-height: 1.45; + word-break: break-word; +} + +.cs-modal-actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 18px; +} + +.cs-modal-actions button { + min-width: 82px; + padding: 9px 14px; + border: 0; + border-radius: 8px; + font-size: 0.8rem; + font-weight: 800; + cursor: pointer; +} + +.cs-modal-cancel { + background: #e2e8f0; + color: #334155; +} + +.cs-modal-save { + background: #2563eb; + color: #fff; +} + +.cs-modal-delete { + background: #dc2626; + color: #fff; +} + +.cs-record-composer { + margin: 15px 22px 12px; + padding: 12px; + border: 1px solid #cbd5e1; + border-radius: 10px; + background: #f8fafc; +} + +.cs-record-composer textarea { + display: block; + width: 100%; + min-height: 64px; + resize: vertical; + border: 0; + outline: 0; + background: transparent; + color: #1e293b; + font-size: 0.88rem; + line-height: 1.55; +} + +.cs-composer-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 8px; +} + +.cs-composer-footer span { + color: #94a3b8; + font-size: 0.62rem; +} + +.cs-primary-button { + padding: 9px 16px; + background: #2563eb; + color: #fff; + font-size: 0.8rem; +} + +.cs-primary-button:hover { + background: #1d4ed8; +} + +.cs-record-list { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 1px 16px 14px; +} + +.cs-record-item { + display: grid; + grid-template-columns: 20px minmax(0, 1fr) auto; + align-items: start; + gap: 4px; + padding: 1px 2px; + border-bottom: 1px solid #e2e8f0; +} + +.cs-record-checkbox { + width: 16px; + height: 16px; + margin-top: 2px; + accent-color: #2563eb; + cursor: pointer; +} + +.cs-record-text { + width: 100%; + min-height: 22px; + resize: none; + overflow: hidden; + border: 1px solid transparent; + border-radius: 6px; + background: transparent; + padding: 1px 5px; + color: #1e293b; + font-size: 0.86rem; + line-height: 1.2; +} + +.cs-record-text:hover, +.cs-record-text:focus { + border-color: #bfdbfe; + background: #f8fbff; + outline: none; +} + +.cs-record-item.completed .cs-record-text { + color: #94a3b8; + text-decoration: line-through; +} + +.cs-record-meta { + display: flex; + align-items: center; + gap: 3px; + padding-top: 0; +} + +.cs-source-badge { + padding: 3px 6px; + border-radius: 999px; + background: #eef2ff; + color: #4338ca; + font-size: 0.58rem; + white-space: nowrap; +} + +.cs-delete-button { + border: 0; + background: transparent; + color: #94a3b8; + font-size: 0.76rem; + cursor: pointer; +} + +.cs-delete-button:hover { + color: #dc2626; +} + +.cs-complete-button { + border: 0; + border-radius: 5px; + background: #e8f1ff; + color: #1d4ed8; + padding: 3px 6px; + font-size: 0.7rem; + font-weight: 700; + white-space: nowrap; + cursor: pointer; +} + +.cs-record-item.completed .cs-complete-button { + background: #e2e8f0; + color: #475569; +} + +.cs-empty-state { + display: grid; + place-items: center; + min-height: 180px; + color: #94a3b8; + font-size: 0.78rem; + text-align: center; +} + +@media (max-width: 900px) { + .cs-record-tab.active { + overflow-y: auto; + } + + .cs-record-layout { + grid-template-columns: 1fr; + height: auto; + min-width: 0; + } + + .cs-calendar-card, + .cs-record-card { + min-height: auto; + } + + .cs-calendar-card { + align-self: start; + } + + .cs-schedule-list { + max-height: 270px; + } + + .cs-record-card, + .cs-permanent-card { + width: 100%; + overflow: visible; + } + + .cs-record-list, + .cs-permanent-list { + overflow: visible; + } +} + +@media (max-width: 560px) { + .cs-record-header { + align-items: flex-start; + flex-direction: column; + } + + .cs-copy-button { + width: 100%; + } + + .cs-schedule-date-row { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .cs-all-day-toggle { + grid-column: 1 / -1; + min-height: 30px; + justify-self: end; + } +} diff --git a/static/css/return_filters.css b/static/css/return_filters.css new file mode 100644 index 0000000..d7f1802 --- /dev/null +++ b/static/css/return_filters.css @@ -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; } diff --git a/static/js/app.js b/static/js/app.js index db52bbb..7b71253 100644 --- a/static/js/app.js +++ b/static/js/app.js @@ -656,7 +656,7 @@ document.addEventListener('DOMContentLoaded', () => { // 이름은 한글 2~5글자를 인식하도록 완화 const nameMatch = trimmed.match(/^[가-힣]{2,5}/); - + if (targetField === 'phone') { const phoneInput = document.getElementById('cust-phone'); if (hasPhone) { @@ -961,7 +961,7 @@ document.addEventListener('DOMContentLoaded', () => { updateOrderGroupBadges(); refreshLiveSmsPreview(); } - + orderItemsContainer.addEventListener('change', function(e) { if (e.target.classList.contains('qty-order') && e.target.tagName === 'SELECT' && e.target.value === 'manual') { const input = document.createElement('input'); @@ -969,7 +969,7 @@ document.addEventListener('DOMContentLoaded', () => { input.min = '1'; input.value = '1'; input.className = 'qty-order'; - + e.target.replaceWith(input); input.focus(); input.select(); @@ -1361,13 +1361,13 @@ document.addEventListener('DOMContentLoaded', () => { } else { itemTotal = cost * qty; } - + const orderType = document.querySelector('input[name="order-type"]:checked').value; const noLidChecked = document.getElementById('chk-no-lid').checked; if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) { itemTotal = 0; } - + if (!excludedIndices.includes(idx)) { totalCost += itemTotal; 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 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 totalAfterDiscount = totalCost; @@ -1476,13 +1476,13 @@ document.addEventListener('DOMContentLoaded', () => { else if (hasMarkedFreeShipping) freeReason = "무료배송상품"; else freeReason = "무료"; } - + let extraShippingCost = 0; if (document.getElementById('sms-ship-extra').checked) { extraShippingCost = extraShippingVal; if (isFreeShip) freeReason += " / 도서산간 추가"; } - + const currentOrderType = document.querySelector('input[name="order-type"]:checked').value; if (SPECIAL_ORDER_TYPES.has(currentOrderType)) { shippingCost = 0; @@ -1539,25 +1539,25 @@ document.addEventListener('DOMContentLoaded', () => { // Setup modal const listContainer = document.getElementById('exclude-items-list'); listContainer.innerHTML = ''; - + const updateTotalDisplay = () => { const excludedIndices = Array.from(document.querySelectorAll('.exclude-chk:checked')).map(c => parseInt(c.dataset.idx)); const livePayload = getOrderPayload(excludedIndices); - + let displayTotal = livePayload.total_amount; const chkSampleSend = document.getElementById('chk-sample-send'); if (chkSampleSend && chkSampleSend.checked) { displayTotal = 0; } - + document.getElementById('exclude-modal-totalAmount').innerText = displayTotal.toLocaleString(); - + let extraDiv = document.getElementById('exclude-extra-items'); if(!extraDiv) { extraDiv = document.createElement('div'); extraDiv.id = 'exclude-extra-items'; } - + let extraHTML = ''; if (livePayload.discount_5_amount > 0) { extraHTML += ` @@ -1624,7 +1624,7 @@ document.addEventListener('DOMContentLoaded', () => { const qty = parseInt(row.querySelector('.qty-order').value) || 1; const multiplier = parseInt(chk.dataset.multiplier) || 1; const finalQty = qty * multiplier; - + const cost = parseInt(chk.dataset.cost) || 0; const dcost = chk.dataset.dcost === "null" ? null : (parseInt(chk.dataset.dcost) || null); let itemTotal = 0; @@ -1633,17 +1633,17 @@ document.addEventListener('DOMContentLoaded', () => { } else { itemTotal = cost * qty; } - + const orderType = document.querySelector('input[name="order-type"]:checked').value; const noLidChecked = document.getElementById('chk-no-lid').checked; if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) { itemTotal = 0; } - + let badges = []; if (SPECIAL_ORDER_TYPES.has(orderType)) badges.push(ORDER_TYPE_LABELS[orderType]); if (noLidChecked && chk.dataset.type === 'ORDER_SINGLE') badges.push('뚜껑(X)통(O)'); - + let reasonBadge = badges.length > 0 ? `${badges.join(', ')}` : ''; const div = document.createElement('div'); @@ -1654,7 +1654,7 @@ document.addEventListener('DOMContentLoaded', () => { div.style.background = '#fff'; div.style.border = '1px solid #cbd5e0'; div.style.borderRadius = '4px'; - + div.innerHTML = ` `; - + const checkbox = div.querySelector('.exclude-chk'); checkbox.addEventListener('change', updateTotalDisplay); - + listContainer.appendChild(div); }); currentSubmitContext = { url, isEllen }; - + const chkSampleSend = document.getElementById('chk-sample-send'); if (chkSampleSend) { chkSampleSend.checked = false; @@ -1680,7 +1680,7 @@ document.addEventListener('DOMContentLoaded', () => { updateTotalDisplay(); }; } - + updateTotalDisplay(); document.getElementById('exclude-modal').style.display = 'flex'; } @@ -1704,10 +1704,10 @@ document.addEventListener('DOMContentLoaded', () => { const isSpecialType = SPECIAL_ORDER_TYPES.has(payload.order_type); const typeLabelMap = ORDER_TYPE_LABELS; - + let finalPayloadAmount = payload.total_amount; if (isSpecialType) finalPayloadAmount = 0; - + const chkSampleSend = document.getElementById('chk-sample-send'); if (chkSampleSend && chkSampleSend.checked) { 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(); if (url.includes('submit')) { const iframe = document.querySelector('#manual-tab iframe'); @@ -1952,7 +1957,7 @@ document.addEventListener('DOMContentLoaded', () => { } else { itemTotal = cost * qty; } - + const orderType = document.querySelector('input[name="order-type"]:checked').value; const noLidChecked = document.getElementById('chk-no-lid').checked; if (SPECIAL_ORDER_TYPES.has(orderType) || noLidChecked) { @@ -2013,12 +2018,12 @@ document.addEventListener('DOMContentLoaded', () => { if (!isFreeShip) { shippingCost = baseShippingVal; } - + let extraShippingCost = 0; if (document.getElementById('sms-ship-extra').checked) { extraShippingCost = extraShippingVal; } - + const currentOrderType = document.querySelector('input[name="order-type"]:checked').value; const noLidChecked = document.getElementById('chk-no-lid').checked; 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 phone = firstNonEmpty(d.custPhone, d.phone, cachedCustomer.custPhone, cachedCustomer.phone); const address = firstNonEmpty(d.custAddress, d.address, cachedCustomer.custAddress, cachedCustomer.address); - + const hasCustInfo = (name && name.trim() && name.trim().toLowerCase() !== 'none') || (phone && phone.trim() && phone.trim().toLowerCase() !== 'none') || (address && address.trim() && address.trim().toLowerCase() !== 'none'); - + let amountStr = d.deposit_amount_str || ''; if (hasCustInfo) { 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 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-extra').value = parseInt(extraShippingVal).toLocaleString(); - + const lblShipExtra = document.getElementById('lbl-ship-extra'); if (lblShipExtra) { lblShipExtra.textContent = '추가배송비 ' + parseInt(extraShippingVal).toLocaleString() + '원'; @@ -2596,7 +2601,7 @@ document.addEventListener('DOMContentLoaded', () => { if (fText) payload.rules['footer_text'] = fText.value; const fontSel = document.getElementById('app-font-select'); if (fontSel) payload.app_settings.font = fontSel.value; - + try { const res = await fetch('/api/gift/settings', { method: 'POST', @@ -2786,7 +2791,7 @@ document.addEventListener('DOMContentLoaded', () => { alert('송장 앞 숫자 저장에 실패했습니다.'); return; } - + const trackingNumbers = lines.map(l => { let val = l.trim(); if (val && savedPrefix && val.length === 8) { @@ -2794,7 +2799,7 @@ document.addEventListener('DOMContentLoaded', () => { } return val; }).filter(l => l); - + if (trackingNumbers.length === 0) { alert('송장번호를 입력해주세요.'); return; @@ -2834,27 +2839,45 @@ document.addEventListener('DOMContentLoaded', () => { } // 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() { const tbody = document.getElementById('tbody-return-requests'); if(!tbody) return; + const version = ++returnHistoryVersions.req; try { - const res = await fetch('/api/return/request'); - const recRes = await fetch('/api/return/receive'); - if(res.ok && recRes.ok) { + const res = await fetch(returnHistoryUrl('req', 'request')); + if (!res.ok) throw new Error('신청 목록을 불러오지 못했습니다.'); + if(res.ok) { const data = await res.json(); - const recData = await recRes.json(); - const receivedTrackingNos = new Set((recData.data || []).map(r => r.tracking_no).filter(t => t)); + if (version !== returnHistoryVersions.req) return; + if (!data.success) throw new Error('신청 목록을 불러오지 못했습니다.'); tbody.innerHTML = ''; if(data.data) { - + const excludeReceived = document.getElementById('chk-exclude-received')?.checked; let displayData = data.data; - if (excludeReceived) { - displayData = displayData.filter(i => !(i.tracking_no && receivedTrackingNos.has(i.tracking_no))); + if (excludeReceived && !returnHistoryQueries.req) { + displayData = displayData.filter(i => !i.is_received); } + returnHistoryStatus('req', displayData.length); + if (!displayData.length) tbody.innerHTML = '