Move CORM settings and histories to dedicated PostgreSQL database
This commit is contained in:
@@ -40,3 +40,4 @@ test.ps1
|
||||
|
||||
# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache)
|
||||
.cache/
|
||||
.settings-backups/
|
||||
|
||||
+8
-1
@@ -13,6 +13,13 @@ ITEMCODE_DB=itemcode_db
|
||||
ORDERLIST_DB=orderlist_db
|
||||
RETURN_DB=return_db
|
||||
|
||||
# CORM 설정·내역 전용 DB (서버/계정은 기존 POSTGRES_* 사용, ITEMCODE_DB와 별개)
|
||||
SETTINGS_DB=corm_db
|
||||
# 설정 저장소: 이전·검증 완료 후 postgres로 변경
|
||||
SETTINGS_BACKEND=google
|
||||
# 문자내역/수동발주내역: history_migrate.py 이전·검증 후 postgres로 변경
|
||||
HISTORY_BACKEND=google
|
||||
|
||||
# ============================================
|
||||
# 네이버 커머스 API
|
||||
# ============================================
|
||||
@@ -73,7 +80,7 @@ WEB_NETWORK=npm_default
|
||||
# CS_RECORD_DB_PASSWORD=
|
||||
# CS 기록 다음 업무일 계산에 더할 휴일(YYYY-MM-DD, 쉼표 구분)
|
||||
# CS_RECORD_EXTRA_HOLIDAYS=
|
||||
# 구글 연동 시간 제한(초)·동시 작업 수, 설정 시트 캐시 유효 시간(초)
|
||||
# 구글 연동 시간 제한(초)·동시 작업 수, google 모드의 설정 캐시 유효 시간(초)
|
||||
# GOOGLE_CONNECT_TIMEOUT=3
|
||||
# GOOGLE_READ_TIMEOUT=10
|
||||
# GOOGLE_WORKERS=4
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
*.sh text eol=lf
|
||||
@@ -47,3 +47,4 @@ test.ps1
|
||||
|
||||
# 구글 설정 마지막 정상값 스냅샷(google_runtime.SettingsCache)
|
||||
.cache/
|
||||
.settings-backups/
|
||||
|
||||
@@ -31,9 +31,14 @@ ERP 연결 실패/타임아웃은 503으로 차단하며, CORM은 ERP 세션을
|
||||
|
||||
## 사용 DB
|
||||
|
||||
구글 시트의 업무 설정을 같은 PostgreSQL 서버의 전용 `corm_db`로 이전하려면 [설정 DB 이전 절차](docs/settings-postgres.md)를 따른다.
|
||||
`SETTINGS_BACKEND=postgres`로 전환한 뒤에는 설정 화면의 조회·저장이 DB를 사용한다. DB 접속 정보와 API 비밀키는 기존 `.env`/환경변수에 유지한다.
|
||||
문자내역과 수동발주내역도 같은 `corm_db`로 옮기려면 [내역 DB 이전 절차](docs/history-postgres.md)를 따르고 `HISTORY_BACKEND=postgres`로 전환한다.
|
||||
|
||||
| DB 이름 | 용도 |
|
||||
|---|---|
|
||||
| `itemcode_db` | 품목코드 마스터 + CS 기록(v9.1: `cs_records`·`cs_memo_folders`·`cs_permanent_memos`·`cs_schedules`, 앱이 처음 쓸 때 `CREATE TABLE IF NOT EXISTS` 로 자동 생성) |
|
||||
| `corm_db` | CORM 업무 설정·문자내역·수동발주내역 (`SETTINGS_DB`, `corm_settings`·`corm_sms_history`·`corm_manual_history` 테이블) |
|
||||
| `orderlist_db` | 주문 정보 조회 |
|
||||
| `return_db` | 반품 데이터 저장 |
|
||||
|
||||
@@ -50,6 +55,19 @@ ERP 연결 실패/타임아웃은 503으로 차단하며, CORM은 ERP 세션을
|
||||
|
||||
## 서버 배포 절차 (`/opt/dbx-corm`)
|
||||
|
||||
### 설정·문자내역·수동발주내역 PostgreSQL 전환 (운영자 실행)
|
||||
|
||||
다른 앱과 시트에서 편집을 잠시 중단한 뒤 서버에서 아래 한 줄을 실행한다. 이미지 빌드 후 CORM 앱을 잠시 정지하며,
|
||||
원본·로컬 내역·환경과 이전 이미지 백업 → `corm_db` 준비 → 전체 데이터 이전·검증 → 환경 전환 → 읽기 API 확인 순서로 진행한다.
|
||||
DB 생성 권한이 없는 계정은 관리자가 먼저 `corm_db`를 생성해야 한다.
|
||||
실패하면 기존 이미지/환경으로 앱 재시작을 시도하고 DB와 백업을 보존한다. 기존 DB 데이터를 덮어쓰거나 삭제하지 않는다.
|
||||
|
||||
```bash
|
||||
cd /opt/dbx-corm && git pull --ff-only && bash deploy-corm-postgres.sh
|
||||
```
|
||||
|
||||
백업은 `.settings-backups/deploy-<시각>-<프로세스번호>/`에 보관된다. 직원 로그인과 실제 화면 동작은 완료 후 별도로 확인한다.
|
||||
|
||||
### 1. 코드 받기
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run by the server operator. No source-sheet writes or database overwrites.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
|
||||
project_dir="$(pwd -P)"
|
||||
test -f .env || { printf '%s\n' '.env 파일이 없습니다.' >&2; exit 1; }
|
||||
git diff --quiet && git diff --cached --quiet || { printf '%s\n' '서버에 커밋되지 않은 코드 변경이 있어 중단합니다.' >&2; exit 1; }
|
||||
docker compose version >/dev/null
|
||||
docker compose ps
|
||||
container="$(docker compose ps -q corm-app)"
|
||||
test -n "$container" || { printf '%s\n' '기존 corm-app 컨테이너가 실행 중이어야 합니다.' >&2; exit 1; }
|
||||
|
||||
# Capture the current runtime, including configurable legacy file locations.
|
||||
runtime="$(docker exec "$container" python -c 'import os; from pathlib import Path; print(os.getenv("SETTINGS_BACKEND", "google")); print(os.getenv("HISTORY_BACKEND", "google")); print(os.getenv("SETTINGS_DB", "corm_db")); print(int(bool(os.getenv("INTERNAL_SERVICE_TOKEN")))); print(os.getenv("SMS_HISTORY_FILE", "/app/sms_history.dat")); print(os.getenv("MANUAL_HISTORY_FILE", "/app/manual_history.dat"))')"
|
||||
mapfile -t runtime_values <<< "$runtime"
|
||||
settings_source="${runtime_values[0]}"
|
||||
history_source="${runtime_values[1]}"
|
||||
[[ "$settings_source" =~ ^(google|postgres)$ && "$history_source" =~ ^(google|postgres)$ ]] || exit 1
|
||||
if [[ "$settings_source" == postgres || "$history_source" == postgres ]]; then
|
||||
[[ "${runtime_values[2]}" == corm_db ]] || { printf '%s\n' '현재 DB 저장소가 corm_db가 아니므로 자동 이전을 중단합니다.' >&2; exit 1; }
|
||||
fi
|
||||
[[ "${runtime_values[3]}" == 1 ]] || { printf '%s\n' '기존 INTERNAL_SERVICE_TOKEN이 없어 전환 후 API를 검증할 수 없습니다.' >&2; exit 1; }
|
||||
|
||||
stamp="$(date -u +%Y%m%dT%H%M%SZ)-$$"
|
||||
backup_dir="$project_dir/.settings-backups/deploy-$stamp"
|
||||
mkdir -p -- "$backup_dir"
|
||||
chmod 700 -- "$backup_dir"
|
||||
cp -p -- .env "$backup_dir/env.before"
|
||||
cp -p -- docker-compose.yml "$backup_dir/compose.before.yml"
|
||||
old_image="$(docker inspect --format '{{.Image}}' "$container")"
|
||||
rollback_image="dbx-corm:before-postgres-$stamp"
|
||||
docker image tag "$old_image" "$rollback_image"
|
||||
printf 'services:\n corm-app:\n image: %s\n' "$rollback_image" > "$backup_dir/rollback.yml"
|
||||
printf '백업 위치: %s\n' "$backup_dir"
|
||||
printf '%s\n' '이미지를 빌드합니다. 이후 이전이 끝날 때까지 다른 앱과 시트에서 설정·내역 편집을 중단해주세요.'
|
||||
docker compose build corm-app
|
||||
|
||||
stopped=0
|
||||
env_changed=0
|
||||
rollback() {
|
||||
result=$?
|
||||
trap - ERR INT TERM
|
||||
printf '전환 실패. 백업 보존 위치: %s\n' "$backup_dir" >&2
|
||||
if [[ "$stopped" == 1 ]]; then
|
||||
if [[ "$env_changed" == 1 ]]; then
|
||||
cp -p -- "$backup_dir/env.before" "$project_dir/.env" || true
|
||||
fi
|
||||
# Reuse the exact former image; never restore/drop the database automatically.
|
||||
if docker compose -f "$project_dir/docker-compose.yml" -f "$backup_dir/rollback.yml" up -d --no-deps --no-build corm-app; then
|
||||
printf '%s\n' '이전 이미지와 환경으로 앱을 다시 시작했습니다. DB와 원본 백업은 보존했습니다.' >&2
|
||||
else
|
||||
printf '%s\n' '앱 자동 재시작을 확인하지 못했습니다. 위 백업의 env.before·rollback.yml을 확인해주세요.' >&2
|
||||
fi
|
||||
fi
|
||||
[[ "$result" != 0 ]] || result=1
|
||||
exit "$result"
|
||||
}
|
||||
trap rollback ERR INT TERM
|
||||
|
||||
# Capture existence before stopping; docker cp also works on stopped containers.
|
||||
sms_exists="$(docker exec "$container" python -c 'import os; from pathlib import Path; print(int(Path(os.getenv("SMS_HISTORY_FILE", "/app/sms_history.dat")).is_file()))')"
|
||||
manual_exists="$(docker exec "$container" python -c 'import os; from pathlib import Path; print(int(Path(os.getenv("MANUAL_HISTORY_FILE", "/app/manual_history.dat")).is_file()))')"
|
||||
stopped=1
|
||||
docker compose stop corm-app
|
||||
if [[ "$sms_exists" == 1 ]]; then
|
||||
docker cp "$container:${runtime_values[4]}" "$backup_dir/legacy-sms.dat"
|
||||
fi
|
||||
if [[ "$manual_exists" == 1 ]]; then
|
||||
docker cp "$container:${runtime_values[5]}" "$backup_dir/legacy-manual.dat"
|
||||
fi
|
||||
printf '로컬 원본 파일: 문자=%s 수동발주=%s\n' "$sms_exists" "$manual_exists"
|
||||
|
||||
run_corm() {
|
||||
docker compose run --rm --no-deps -T \
|
||||
-e SETTINGS_DB=corm_db -e SETTINGS_BACKEND=google -e HISTORY_BACKEND=google \
|
||||
-v "$backup_dir:/backups" -v "$project_dir:/deploy" corm-app python deploy_corm.py "$@"
|
||||
}
|
||||
run_corm snapshot --settings-source "$settings_source" --history-source "$history_source"
|
||||
run_corm database
|
||||
run_corm migrate
|
||||
env_changed=1
|
||||
run_corm environment
|
||||
docker compose up -d --no-deps --no-build corm-app
|
||||
|
||||
ready=0
|
||||
for attempt in {1..12}; do
|
||||
if docker compose exec -T corm-app python deploy_corm.py probe; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
[[ "$ready" == 1 ]]
|
||||
trap - ERR INT TERM
|
||||
docker compose ps
|
||||
printf 'CORM 설정·문자내역·수동발주내역 corm_db 전환 완료. 백업: %s\n' "$backup_dir"
|
||||
printf '%s\n' '직원 계정으로 로그인해 화면에서 내역 불러오기와 설정을 확인해주세요.'
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
"""Container-side steps for the operator-run CORM PostgreSQL deployment."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg2
|
||||
from psycopg2 import sql
|
||||
from dotenv import set_key
|
||||
|
||||
from history_migrate import load_backup, read_source
|
||||
from history_store import PostgresHistoryStore, validate_bundle
|
||||
from settings_migrate import load_snapshot, read_google_rows, save_snapshot
|
||||
from settings_store import PostgresSettingsStore, SettingsNotInitialized, settings_db_config
|
||||
|
||||
|
||||
def ensure_database():
|
||||
config = settings_db_config()
|
||||
if config["dbname"] != "corm_db":
|
||||
raise ValueError("배포 대상은 corm_db여야 합니다.")
|
||||
admin_config = {**config, "dbname": "postgres"}
|
||||
with closing(psycopg2.connect(**admin_config, connect_timeout=3)) as connection:
|
||||
connection.autocommit = True
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (config["dbname"],))
|
||||
if cursor.fetchone() is None:
|
||||
cursor.execute(sql.SQL("CREATE DATABASE {} OWNER {}")
|
||||
.format(sql.Identifier(config["dbname"]), sql.Identifier(config["user"])))
|
||||
print("corm_db 생성 완료.")
|
||||
else:
|
||||
print("기존 corm_db 사용. 기존 데이터는 덮어쓰지 않습니다.")
|
||||
|
||||
|
||||
def snapshot(directory, settings_source="google", history_source="google"):
|
||||
directory = Path(directory)
|
||||
if settings_source == "postgres":
|
||||
rows, _ = PostgresSettingsStore(settings_db_config()).read()
|
||||
source = "postgres:corm_db:settings"
|
||||
else:
|
||||
rows, source = read_google_rows()
|
||||
save_snapshot(directory / "settings-source.json", rows, source)
|
||||
if history_source == "postgres":
|
||||
bundle = PostgresHistoryStore(settings_db_config()).export_all()
|
||||
source = "postgres:corm_db:histories"
|
||||
else:
|
||||
sms = directory / "legacy-sms.dat"
|
||||
manual = directory / "legacy-manual.dat"
|
||||
bundle, source = read_source(str(sms) if sms.exists() else None,
|
||||
str(manual) if manual.exists() else None)
|
||||
save_snapshot(directory / "history-source.json", bundle, source)
|
||||
# Container-created backups should remain readable by the server operator.
|
||||
owner = directory.stat()
|
||||
for name in ("settings-source.json", "history-source.json"):
|
||||
os.chown(directory / name, owner.st_uid, owner.st_gid)
|
||||
print(f"원본 백업 완료: 설정 {len(rows)}행 / 문자 {len(bundle['sms'])}건 / 수동발주 {len(bundle['manual'])}건.")
|
||||
|
||||
|
||||
def migrate(directory):
|
||||
directory = Path(directory)
|
||||
rows, source = load_snapshot(directory / "settings-source.json")
|
||||
bundle, history_source = load_backup(directory / "history-source.json")
|
||||
settings = PostgresSettingsStore(settings_db_config())
|
||||
histories = PostgresHistoryStore(settings_db_config())
|
||||
try:
|
||||
settings.read()
|
||||
except SettingsNotInitialized:
|
||||
settings.import_rows(rows, source)
|
||||
if settings.read()[0] != rows:
|
||||
raise RuntimeError("기존 DB 설정과 원본이 다릅니다. 덮어쓰지 않고 중단합니다.")
|
||||
try:
|
||||
histories.check_ready()
|
||||
except (SettingsNotInitialized, psycopg2.errors.UndefinedTable):
|
||||
histories.import_all(bundle, history_source)
|
||||
if validate_bundle(histories.export_all()) != validate_bundle(bundle):
|
||||
raise RuntimeError("기존 DB 내역과 원본이 다릅니다. 덮어쓰지 않고 중단합니다.")
|
||||
print("설정·문자내역·수동발주내역 전체 데이터 검증 완료.")
|
||||
|
||||
|
||||
def switch_environment(path):
|
||||
target = Path(path)
|
||||
before = target.stat()
|
||||
for key, value in (("SETTINGS_DB", "corm_db"), ("SETTINGS_BACKEND", "postgres"), ("HISTORY_BACKEND", "postgres")):
|
||||
set_key(target, key, value, quote_mode="never")
|
||||
os.chmod(target, 0o600)
|
||||
os.chown(target, before.st_uid, before.st_gid)
|
||||
print("설정·내역 저장소를 corm_db로 전환했습니다.")
|
||||
|
||||
|
||||
def probe():
|
||||
import requests
|
||||
if os.getenv("SETTINGS_BACKEND") != "postgres" or os.getenv("HISTORY_BACKEND") != "postgres":
|
||||
raise RuntimeError("앱 저장소 환경이 아직 postgres가 아닙니다.")
|
||||
settings = PostgresSettingsStore(settings_db_config())
|
||||
settings.read()
|
||||
PostgresHistoryStore(settings_db_config()).check_ready()
|
||||
token = os.getenv("INTERNAL_SERVICE_TOKEN", "")
|
||||
if not token:
|
||||
raise RuntimeError("API 검증용 기존 INTERNAL_SERVICE_TOKEN이 없습니다.")
|
||||
headers = {"X-Service-Token": token}
|
||||
for path in ("/api/config", "/api/sms/history", "/api/manual/history"):
|
||||
response = requests.get("http://127.0.0.1:8002" + path, headers=headers, timeout=5)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
if path == "/api/config":
|
||||
if response.headers.get("X-Settings-Backend") != "postgres" or not isinstance(data, dict):
|
||||
raise RuntimeError("설정 API 저장소 검증 실패.")
|
||||
elif not isinstance(data, list):
|
||||
raise RuntimeError("내역 API 검증 실패.")
|
||||
print("DB 및 설정·문자내역·수동발주내역 API 조회 정상.")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description="CORM 운영자 배포 스크립트 내부 단계")
|
||||
parser.add_argument("step", choices=("snapshot", "database", "migrate", "environment", "probe"))
|
||||
parser.add_argument("--directory", default="/backups")
|
||||
parser.add_argument("--env-path", default="/deploy/.env")
|
||||
parser.add_argument("--settings-source", choices=("google", "postgres"), default="google")
|
||||
parser.add_argument("--history-source", choices=("google", "postgres"), default="google")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.step == "snapshot":
|
||||
snapshot(args.directory, args.settings_source, args.history_source)
|
||||
elif args.step == "database":
|
||||
ensure_database()
|
||||
elif args.step == "migrate":
|
||||
migrate(args.directory)
|
||||
elif args.step == "environment":
|
||||
switch_environment(args.env_path)
|
||||
else:
|
||||
probe()
|
||||
return 0
|
||||
except Exception as exc:
|
||||
# Do not print credentials, customer records or request headers.
|
||||
print(f"배포 단계 실패: {args.step} ({type(exc).__name__}). 원본/접속/DB 권한을 확인해주세요.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,100 @@
|
||||
# 문자내역·수동발주내역을 corm_db로 이전
|
||||
|
||||
설정은 `corm_settings`, 문자내역은 `corm_sms_history`, 수동발주내역은 `corm_manual_history`에 저장한다.
|
||||
서버와 계정은 기존 `POSTGRES_*`, DB 이름은 `SETTINGS_DB=corm_db`를 공통 사용한다.
|
||||
기존 `itemcode_db`의 코드표와 CS 기록은 그대로 유지한다.
|
||||
|
||||
## 동작
|
||||
|
||||
- `HISTORY_BACKEND=postgres`이면 두 내역의 조회·저장과 문자내역 삭제는 DB만 사용한다. 기존 `.dat`와 내역 시트에는 추가로 쓰지 않는다.
|
||||
- 문자 내역의 고객 정보·상품 목록·할인/배송 옵션·문자 전문을 JSONB에 보존한다. 기록마다 고유 ID를 부여해 목록 순서가 바뀌어도 같은 내역을 선택·삭제한다.
|
||||
- 수동발주내역은 기존처럼 한국 시간의 오늘 내역을 표시한다. DB에는 과거 내역도 모두 보관하며 날짜가 바뀌어도 삭제하지 않는다.
|
||||
- 실제 발주 입력/엑셀 다운로드에 사용하는 별도 **수동 발주** 시트는 계속 사용한다.
|
||||
- 기존 수동발주 삭제는 발주 시트의 주문 행도 지우는 기능이다. DB 모드에서도 해당 주문 행 삭제를 확인한 뒤 내역을 삭제한다. 구글 장애 시 DB 내역을 보존하고 오류를 표시한다.
|
||||
- 같은 일시의 내역이 여러 건이면 주문을 잘못 취소하지 않도록 자동 삭제를 중단한다. 발주 시트에서 대상 주문을 먼저 확인해야 한다.
|
||||
- 구글 발주 시트 삭제와 DB 삭제는 서로 다른 서비스라 하나의 트랜잭션으로 묶이지 않는다. 시트 삭제 후 DB 오류가 발생하면 시트의 주문 상태를 확인하고 재시도한다. 없는 시트 행은 재삭제하지 않는다.
|
||||
- DB 장애를 저장 성공으로 표시하거나 예전 시트/파일로 자동 우회하지 않는다.
|
||||
|
||||
## 원본 준비
|
||||
|
||||
구글 시트에는 상품·문자 텍스트 위주로 저장되고, `.dat` 파일에 상세 상품 목록과 옵션이 더 남아 있을 수 있다.
|
||||
따라서 **실제 운영 중인 컨테이너의 로컬 내역 파일도 함께 가져와야 한다.** 새 일회용 컨테이너에는 이 파일이 자동 복사되지 않는다.
|
||||
|
||||
아래는 Linux 서버 프로젝트 폴더에서 실행하는 명령이다. 먼저 [설정 DB 이전 문서](settings-postgres.md)에 따라
|
||||
`corm_db`를 준비하고 새 코드를 빌드한다. `.env`에는 `SETTINGS_DB=corm_db`를 지정하고, 내역 모드는 아직 `HISTORY_BACKEND=google`로 유지한다.
|
||||
|
||||
1. 직원 및 다른 구버전 앱의 문자 생성·발주·내역 저장·삭제와 시트 직접 편집을 잠시 중단하고, 앱을 정지한다.
|
||||
|
||||
```bash
|
||||
mkdir -p .settings-backups
|
||||
docker compose stop corm-app
|
||||
```
|
||||
|
||||
2. 기존 컨테이너에서 원본 파일을 호스트로 복사한다. 아래는 기본 경로 예시다.
|
||||
`SMS_HISTORY_FILE`·`MANUAL_HISTORY_FILE`을 따로 지정했다면 해당 경로를 사용한다.
|
||||
정지된 컨테이너에서도 `docker cp`가 가능하다. 파일이 없다는 오류가 나면 실제 운영 경로부터 확인한다.
|
||||
|
||||
```bash
|
||||
docker cp dbx-corm:/app/sms_history.dat .settings-backups/legacy-sms.dat
|
||||
docker cp dbx-corm:/app/manual_history.dat .settings-backups/legacy-manual.dat
|
||||
```
|
||||
|
||||
원래 해당 로컬 파일이 존재하지 않았다면 그 파일의 복사와 다음 명령의 해당 `--*-local-file` 인자를 생략한다.
|
||||
파일이 없으면 시트에 남은 정보만 이전할 수 있다. 브라우저에만 남아 있는 고객 캐시는 자동 이전하지 않는다.
|
||||
|
||||
3. 구글의 **문자내역·수동발주내역 전체**와 로컬 파일을 읽어 원본 백업을 생성한다. DB에는 접속하지 않는다.
|
||||
|
||||
```bash
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python history_migrate.py snapshot --sms-local-file /backups/legacy-sms.dat --manual-local-file /backups/legacy-manual.dat --output /backups/history-source.json
|
||||
```
|
||||
|
||||
출력된 두 내역 건수와 로컬 파일 유무를 확인한다. 개인 정보나 문자 내용은 콘솔에 출력하지 않는다.
|
||||
같은 일시의 시트·로컬 기록은 다른 필드도 비교해 한 건씩 병합하고, 매칭되지 않은 기록과 로컬에만 저장된 기록도 보존한다.
|
||||
같은 일시라는 이유만으로 여러 기록을 한 건으로 합치지 않는다. 형식이 깨진 로컬 JSON은 조용히 누락시키지 않고 이전을 중단한다.
|
||||
백업에는 원본 전체 행·셀과 로컬 기록도 포함된다. 백업 경로는 덮어쓰지 않으므로 재실행 시 새 파일명을 사용한다.
|
||||
|
||||
4. 백업에서 DB로 이전하고 원본과 전체 내역을 검증한다.
|
||||
|
||||
```bash
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python history_migrate.py import --input-file /backups/history-source.json --apply --backup /backups/before-history-db.json
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python history_migrate.py verify --input-file /backups/history-source.json
|
||||
```
|
||||
|
||||
두 테이블의 생성·저장·전체 검증은 하나의 DB 트랜잭션으로 처리한다. 이미 내역이 있으면 덮어쓰거나 중복으로 추가하지 않는다.
|
||||
빈 원본도 이전 완료 상태로 기록한다. 이전 완료 후 내역을 지웠더라도 재가져오기로 삭제한 내역이 되살아나지 않는다.
|
||||
|
||||
5. `.env`를 변경하고 앱을 기동한다. 설정도 함께 전환했다면 다음 세 값을 사용한다.
|
||||
|
||||
```dotenv
|
||||
SETTINGS_DB=corm_db
|
||||
SETTINGS_BACKEND=postgres
|
||||
HISTORY_BACKEND=postgres
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose up -d --no-deps corm-app
|
||||
docker compose logs --tail=100 corm-app
|
||||
```
|
||||
|
||||
두 내역 테이블과 이전 완료 표시가 없으면 기동이 실패한다. 기존 브라우저 탭은 새로고침해 새 ID 기반 동작을 사용한다.
|
||||
직원 계정으로 과거 문자 불러오기, 고객 정보·문자 옵션 복원, 새 문자내역 저장 및 오늘의 수동발주 내역 표시를 확인한다.
|
||||
실제 주문 취소를 수반하는 수동발주 삭제 검증에는 테스트 주문을 사용한다.
|
||||
운영 DB에는 자동 테스트를 실행하지 않는다.
|
||||
|
||||
설정을 이미 DB로 이전했다면 설정 이전을 반복할 필요는 없다. 이번에는 위 내역 이전과 `HISTORY_BACKEND` 전환만 진행한다.
|
||||
|
||||
## 백업과 복귀
|
||||
|
||||
정기 백업은 `corm_db` 전체를 포함한다. 내역을 JSON으로 별도 보관하려면 다음을 실행한다.
|
||||
|
||||
```bash
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python history_migrate.py export --output /backups/current-histories.json
|
||||
```
|
||||
|
||||
항상 새 파일명을 사용하고 고객 정보가 포함된 백업의 접근 권한을 제한한다. `.settings-backups/`는 Git과 이미지 빌드에서 제외된다.
|
||||
이 JSON도 `import --input-file`로 **아직 내역이 없는 DB**에 복구할 수 있다. 기존 DB 덮어쓰기는 지원하지 않는다.
|
||||
|
||||
전환 직후 복귀가 필요하면 `HISTORY_BACKEND=google`로 바꾸고 컨테이너를 재생성한다.
|
||||
DB 전환 후의 추가·삭제는 기존 시트/파일에 복제되지 않으므로 복귀 전 DB 내역을 내보내 보관한다.
|
||||
이전 때 복사한 `.dat`는 백업이며, Google 모드에서 로컬 상세 복원을 계속 사용하려면 원래 경로에 마운트하거나 복원해야 한다.
|
||||
DB 전환 후 변경이 있었다면 양쪽 자료의 차이를 검토해 복구해야 한다.
|
||||
@@ -0,0 +1,131 @@
|
||||
# 구글 시트 설정을 PostgreSQL로 이전
|
||||
|
||||
## 이전 범위와 저장 구조
|
||||
|
||||
- 대상: `CS 통합 프로그램 설정` 스프레드시트의 **설정** 탭 전체.
|
||||
- 상품 그룹·상품 코드/이름/가격·정렬·구분선·소그룹 이름·사은품 규칙·문자 문구·배송비·폰트·송장 접두어를 보존한다.
|
||||
- 같은 PostgreSQL 서버의 별도 DB `corm_db` 안에 `corm_settings` 테이블로 저장한다. DB 이름은 `SETTINGS_DB`로 지정하며 기본값은 `corm_db`이다. 기존 `ITEMCODE_DB`와 코드표/CS 기록 테이블은 수정하지 않는다.
|
||||
- 설정 전체를 JSONB 배열로 저장하므로 행과 셀 순서를 보존한다. DB 버전을 함께 비교해 동시 저장의 조용한 덮어쓰기를 차단한다.
|
||||
- DB 모드는 요청마다 작은 설정 문서 1건을 읽는다. 프로세스별 캐시 차이 없이 최신 커밋 값을 사용하며, 구글 요청/구글 작업 풀/구글 설정 캐시는 사용하지 않는다.
|
||||
- DB 장애 시에는 503을 반환한다. 구글의 오래된 설정으로 자동 전환하지 않는다.
|
||||
- DB 접속 정보와 API 비밀키는 계속 `.env`/환경변수에 둔다. `.env`를 DB로 복사하는 처리는 없다.
|
||||
- 이 도구는 `설정` 탭을 이전한다. `문자내역`, `수동발주내역`은 [내역 DB 이전 절차](history-postgres.md)에 따라 같은 `corm_db`로 별도 이전한다. `아이템코드` 탭은 사용하지 않는다.
|
||||
- 실제 수동발주 시트와 밀크런 등 다른 구글 연동에는 계속 구글 인증이 필요하다.
|
||||
|
||||
구글 시트의 탭과 DB 테이블을 반드시 1:1로 맞출 필요는 없다. 현재 업무 설정은 **설정** 탭 안에서
|
||||
`APP_SETTINGS`, `GROUP_NAMES`, `ORDER_*`, `SMS_GIFT_RULES` 등의 분류로 구분되어 있다.
|
||||
이 분류와 상품 순서를 그대로 저장하므로 하나의 `corm_settings` 테이블을 사용해도 설정이 서로 섞이지 않는다.
|
||||
`문자내역`과 `수동발주내역`은 설정이 아닌 이력 데이터이므로 같은 DB 안의 `corm_sms_history`, `corm_manual_history` 테이블로 구분한다.
|
||||
|
||||
## 운영 서버 전환 순서
|
||||
|
||||
아래 명령은 Linux 운영 서버의 프로젝트 폴더(`/opt/dbx-corm`)에서 실행한다.
|
||||
이 문서의 명령을 실행하기 전까지 현재 동작은 바뀌지 않는다. 기본값은 `SETTINGS_BACKEND=google`이다.
|
||||
기존 `.env`를 예제 파일로 덮어쓰지 말고 필요한 항목만 추가한다.
|
||||
|
||||
먼저 PostgreSQL 관리 계정으로 **같은 서버에** `corm_db`를 생성한다. 기존 DB는 이동하거나 변경하지 않는다.
|
||||
아래는 앱 DB 계정이 `king`일 때의 SQL 예시다. 실제 `POSTGRES_USER`가 다르면 소유자를 맞춘다.
|
||||
이미 DB가 있다면 생성 명령을 다시 실행하지 말고 소유자와 접근 권한을 확인한다.
|
||||
|
||||
```sql
|
||||
CREATE DATABASE corm_db OWNER king;
|
||||
```
|
||||
|
||||
앱 계정에 DB 생성 권한을 추가할 필요는 없다. 관리자가 DB를 생성하고 앱 계정에는 해당 DB 접근 및 테이블 생성/읽기/쓰기 권한을 부여한다.
|
||||
앱과 이전 도구는 DB를 자동 생성하지 않는다.
|
||||
이전 명령을 실행하기 **전에** 서버 `.env`에 아래 값을 추가한다. 이 단계에서는 저장소 모드는 `google`로 유지한다.
|
||||
|
||||
```dotenv
|
||||
ITEMCODE_DB=itemcode_db
|
||||
SETTINGS_DB=corm_db
|
||||
SETTINGS_BACKEND=google
|
||||
```
|
||||
|
||||
1. 코드를 서버에 반영하고 새 이미지를 빌드한다. 기존 앱은 아직 구글 모드로 실행된다.
|
||||
|
||||
```bash
|
||||
docker compose build corm-app
|
||||
```
|
||||
|
||||
2. 원본 읽기 및 형식 점검을 실행한다. 이 명령은 DB에 접속하거나 데이터를 쓰지 않는다.
|
||||
|
||||
```bash
|
||||
docker compose run --rm --no-deps corm-app python settings_migrate.py import
|
||||
```
|
||||
|
||||
3. 직원에게 설정 편집을 잠시 멈추도록 알리고, 직접 시트 편집과 다른 구버전 앱의 설정 저장도 중단한다.
|
||||
이전 완료 후 DB 모드로 기동할 때까지 이 상태를 유지한다.
|
||||
현재 앱을 정지하고 원본 JSON을 서버 호스트에 백업한 뒤 DB에 저장한다.
|
||||
|
||||
```bash
|
||||
mkdir -p .settings-backups
|
||||
docker compose stop corm-app
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python settings_migrate.py import --apply --backup /backups/before-postgres.json
|
||||
docker compose run --rm --no-deps corm-app python settings_migrate.py verify
|
||||
```
|
||||
|
||||
`verify`가 **원본과 DB 전체 행·셀·순서 일치**를 출력해야 한다.
|
||||
`--apply`는 백업을 먼저 생성하고, 테이블 생성·최초 저장·전체 데이터 검증을 하나의 DB 트랜잭션으로 처리한다.
|
||||
이미 DB 설정이 있거나 백업 경로가 존재하면 덮어쓰지 않고 중단한다.
|
||||
실패하면 원인을 확인한다. DB가 비어 있는 경우에는 새 백업 경로로 다시 실행할 수 있다.
|
||||
|
||||
4. 이전·검증 완료 후 운영 서버 `.env`의 저장소 모드를 변경한다. DB 계정은 `corm_db`에 테이블을 생성하고 읽고 쓸 수 있어야 한다.
|
||||
|
||||
```dotenv
|
||||
SETTINGS_DB=corm_db
|
||||
SETTINGS_BACKEND=postgres
|
||||
```
|
||||
|
||||
기존 `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_USER`, `POSTGRES_PASSWORD`, `ITEMCODE_DB`와
|
||||
`NAVER_*`, `CAFE24_*`, 구글 인증 설정은 그대로 유지한다.
|
||||
|
||||
5. 앱을 기동하고 상태 및 실제 사용자 화면을 확인한다.
|
||||
|
||||
```bash
|
||||
docker compose up -d --no-deps corm-app
|
||||
docker compose ps
|
||||
docker compose logs --tail=100 corm-app
|
||||
```
|
||||
|
||||
초기화되지 않은 DB에서는 시작이 실패한다. 먼저 이전이 완료되었는지 확인한다.
|
||||
권한이 있는 직원으로 로그인해 상품 순서·가격·배송비·문자 문구를 확인하고,
|
||||
설정 저장 후 새로고침으로 반영 여부를 확인한다. 저장 충돌이나 DB 장애 안내가 보이면 저장을 재시도하기 전에 새로고침한다.
|
||||
브라우저 개발자 도구의 `/api/config` 응답 헤더 `X-Settings-Backend: postgres`로 저장소를 확인할 수 있다.
|
||||
`/health/db` 확인만으로 사용자 설정 조회·저장 검증을 대신하지 않는다.
|
||||
|
||||
이후 설정은 프로그램 화면에서 수정한다. 구글 시트 설정 탭의 변경은 DB에 자동 반영되지 않는다.
|
||||
|
||||
## 백업과 복구
|
||||
|
||||
정기 PostgreSQL 백업에 **`corm_db`**와 그 안의 `corm_settings` 테이블을 포함한다.
|
||||
기존 `itemcode_db`만 백업하면 CORM 설정은 보관되지 않는다. 최신 설정을 JSON으로 내보낼 수도 있다.
|
||||
|
||||
```bash
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python settings_migrate.py export --output /backups/current-settings.json
|
||||
```
|
||||
|
||||
이 명령도 기존 파일은 덮어쓰지 않는다. 매번 새 파일명을 사용한다.
|
||||
백업에는 업무 설정과 문자 문구가 있으므로 접근을 제한한다. `.settings-backups/`는 Git과 Docker 빌드에서 제외되어 있다.
|
||||
파일을 호스트에 보관하려면 위와 같이 반드시 백업 디렉터리를 마운트한다.
|
||||
|
||||
빈 DB에 JSON 백업을 복구할 때는 다음 명령을 사용한다. 기존 DB 설정은 덮어쓰지 않는다.
|
||||
|
||||
```bash
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python settings_migrate.py import --input-file /backups/current-settings.json --apply --backup /backups/before-restore.json
|
||||
docker compose run --rm --no-deps -v "$PWD/.settings-backups:/backups" corm-app python settings_migrate.py verify --input-file /backups/current-settings.json
|
||||
```
|
||||
|
||||
전환 직후 문제가 생기면 `.env`를 `SETTINGS_BACKEND=google`로 되돌리고 컨테이너를 재생성할 수 있다.
|
||||
구글 시트 원본은 그대로 남아 있다. **DB 전환 후 새로 저장한 내용은 구글에 복제되지 않으므로**,
|
||||
변경이 있었다면 우선 위 `export`로 최신 DB 설정을 보관한다. 단순 모드 복귀 시에는 구글에 남은 이전 값이 표시된다.
|
||||
구글 모드에서 다시 수정한 내용을 기존 DB로 재이전하려면 별도로 차이를 검토해야 한다. 자동 덮어쓰기는 지원하지 않는다.
|
||||
|
||||
## 로컬 검증
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
외부 연결 없이 설정 API·순서 보존·구글 작업 풀 분리·오류·충돌·백업/이전 절차를 검증한다.
|
||||
실제 PostgreSQL 검증은 운영 DB가 아닌 폐기 가능한 테스트 DB의 DSN을 `SETTINGS_TEST_DSN`에 지정한 뒤 같은 명령을 실행한다.
|
||||
통합 테스트는 매번 별도의 임시 스키마를 만들고 그 스키마만 제거한다. 테스트 계정에는 스키마 생성 권한이 필요하다.
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Back up, merge and import both Google history tabs into corm_db once."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from history_store import PostgresHistoryStore, merge_sheet_and_local, validate_bundle
|
||||
from settings_migrate import BASE_DIR, fingerprint, save_snapshot
|
||||
from settings_store import SettingsAlreadyInitialized, SettingsNotInitialized, settings_db_config
|
||||
|
||||
|
||||
def read_local_records(path):
|
||||
target = Path(path)
|
||||
if not target.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in target.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def read_source(sms_local_file=None, manual_local_file=None):
|
||||
import main
|
||||
sms_path = Path(sms_local_file or main.SMS_HISTORY_FILE)
|
||||
manual_path = Path(manual_local_file or main.MANUAL_HISTORY_FILE)
|
||||
# Explicit source paths must exist; a missing mounted file must not lose detail silently.
|
||||
for explicit_path in (sms_local_file, manual_local_file):
|
||||
if explicit_path and not Path(explicit_path).is_file():
|
||||
raise FileNotFoundError("지정한 로컬 내역 파일이 없습니다.")
|
||||
local_sms = read_local_records(sms_path)
|
||||
local_manual = read_local_records(manual_path)
|
||||
spreadsheet = main.get_gspread_client().open_by_key(main.SETTINGS_SPREADSHEET_ID)
|
||||
sms_rows = spreadsheet.worksheet("문자내역").get_all_values()
|
||||
manual_rows = spreadsheet.worksheet("수동발주내역").get_all_values()
|
||||
bundle = {
|
||||
"kind": "corm-history",
|
||||
"sms": merge_sheet_and_local("sms", sms_rows, local_sms),
|
||||
"manual": merge_sheet_and_local("manual", manual_rows, local_manual),
|
||||
# Keep complete source material, including unused columns and local-only records.
|
||||
"source_rows": {"문자내역": sms_rows, "수동발주내역": manual_rows},
|
||||
"local_records": {"sms": local_sms, "manual": local_manual},
|
||||
"local_files_found": {"sms": sms_path.is_file(), "manual": manual_path.is_file()},
|
||||
}
|
||||
return bundle, "google:" + main.SETTINGS_SPREADSHEET_ID + ":histories+local"
|
||||
|
||||
|
||||
def load_backup(path):
|
||||
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
bundle = payload["rows"]
|
||||
if payload.get("format") != 1 or payload.get("sha256") != fingerprint(bundle):
|
||||
raise ValueError("내역 백업 체크섬이 올바르지 않습니다.")
|
||||
validate_bundle(bundle)
|
||||
return bundle, "history-backup-file"
|
||||
|
||||
|
||||
def build_store():
|
||||
return PostgresHistoryStore(settings_db_config())
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
load_dotenv(BASE_DIR / ".env")
|
||||
parser = argparse.ArgumentParser(description="문자내역·수동발주내역 → corm_db 이전 / 검증 / 백업")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
importer = commands.add_parser("import", help="기본은 점검만, --apply일 때만 DB 저장")
|
||||
importer.add_argument("--apply", action="store_true")
|
||||
importer.add_argument("--backup")
|
||||
importer.add_argument("--input-file")
|
||||
verifier = commands.add_parser("verify", help="전체 내역과 순서를 검증")
|
||||
verifier.add_argument("--input-file")
|
||||
snapshot = commands.add_parser("snapshot", help="DB에 접속하지 않고 시트·로컬 원본 백업")
|
||||
snapshot.add_argument("--output", required=True)
|
||||
for command in (importer, verifier, snapshot):
|
||||
command.add_argument("--sms-local-file", help="기존 sms_history.dat 파일 경로")
|
||||
command.add_argument("--manual-local-file", help="기존 manual_history.dat 파일 경로")
|
||||
exporter = commands.add_parser("export", help="DB 내역 전체 백업")
|
||||
exporter.add_argument("--output", required=True)
|
||||
args = parser.parse_args(argv)
|
||||
if args.command == "import" and args.apply and not args.backup:
|
||||
parser.error("--apply에는 --backup 경로가 필요합니다.")
|
||||
try:
|
||||
if args.command == "export":
|
||||
bundle = build_store().export_all()
|
||||
save_snapshot(args.output, bundle, "postgres:histories")
|
||||
print(f"내역 백업 완료: 문자 {len(bundle['sms'])}건 / 수동발주 {len(bundle['manual'])}건.")
|
||||
return 0
|
||||
bundle, source = (load_backup(args.input_file) if getattr(args, "input_file", None) else
|
||||
read_source(args.sms_local_file, args.manual_local_file))
|
||||
expected = validate_bundle(bundle)
|
||||
print(f"원본 확인: 문자 {len(expected['sms'])}건 / 수동발주 {len(expected['manual'])}건.")
|
||||
if "local_files_found" in bundle:
|
||||
for kind, label in (("sms", "문자"), ("manual", "수동발주")):
|
||||
state = "있음" if bundle["local_files_found"][kind] else "없음"
|
||||
print(f"로컬 {label} 파일: {state} ({len(bundle['local_records'][kind])}건).")
|
||||
if args.command == "snapshot":
|
||||
save_snapshot(args.output, bundle, source)
|
||||
print("시트·로컬 원본 백업 완료. DB·구글 시트에 쓰지 않았습니다.")
|
||||
return 0
|
||||
if args.command == "verify":
|
||||
if validate_bundle(build_store().export_all()) != expected:
|
||||
print("검증 실패: 원본과 DB 내역이 다릅니다. 전환 전에 차이를 확인해주세요.", file=sys.stderr)
|
||||
return 1
|
||||
print("원본과 DB 전체 내역·순서 일치.")
|
||||
elif args.apply:
|
||||
save_snapshot(args.backup, bundle, source)
|
||||
build_store().import_all(bundle, source)
|
||||
print("두 내역의 DB 이전 및 트랜잭션 내 전체 검증 완료.")
|
||||
else:
|
||||
print("점검만 완료했습니다. DB·구글 시트에 쓰지 않았습니다.")
|
||||
return 0
|
||||
except (SettingsAlreadyInitialized, SettingsNotInitialized) as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
except Exception as exc:
|
||||
# Never print customer information, source rows or connection credentials.
|
||||
print(f"작업 실패 ({type(exc).__name__}). 접속 환경·원본·로컬 내역·백업 경로를 확인해주세요.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,216 @@
|
||||
"""CORM histories: stable record IDs and complete payloads in the CORM database."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from contextlib import closing
|
||||
|
||||
from psycopg2 import sql
|
||||
from psycopg2.extras import Json, execute_values
|
||||
|
||||
from settings_store import PostgresSettingsStore, SettingsAlreadyInitialized, SettingsNotInitialized
|
||||
|
||||
|
||||
TABLES = {"sms": "corm_sms_history", "manual": "corm_manual_history"}
|
||||
|
||||
|
||||
def first_value(data, *keys):
|
||||
for key in keys:
|
||||
value = data.get(key)
|
||||
if value is not None and str(value).strip():
|
||||
return str(value)
|
||||
return ""
|
||||
|
||||
|
||||
def normalize_record(kind, data):
|
||||
if kind not in TABLES or not isinstance(data, dict):
|
||||
raise ValueError("올바른 내역 객체가 필요합니다.")
|
||||
record = copy.deepcopy(data)
|
||||
record.pop("id", None)
|
||||
timestamp = record.get("timestamp")
|
||||
if not isinstance(timestamp, str) or not timestamp.strip():
|
||||
raise ValueError("내역에 일시가 필요합니다.")
|
||||
if kind == "sms":
|
||||
for short, alias, keys in (
|
||||
("custName", "customer_name", ("custName", "customer_name", "customerName", "name")),
|
||||
("custPhone", "phone", ("custPhone", "phone", "customer_phone", "customerPhone")),
|
||||
("custAddress", "address", ("custAddress", "address", "customer_address", "customerAddress")),
|
||||
):
|
||||
record[short] = record[alias] = first_value(record, *keys)
|
||||
if not record.get("items_str"):
|
||||
items = record.get("items") or []
|
||||
if not isinstance(items, list) or not all(isinstance(item, dict) for item in items):
|
||||
raise ValueError("상품 목록 형식이 올바르지 않습니다.")
|
||||
record["items_str"] = ", ".join(
|
||||
f"{item.get('label', '')}[{item.get('code', '')}] {item.get('qty', 0)}개"
|
||||
for item in items
|
||||
)
|
||||
# Validate before DB writes; reject non-JSON payloads rather than losing fields.
|
||||
json.dumps(record, ensure_ascii=False, allow_nan=False)
|
||||
return record
|
||||
|
||||
|
||||
def sheet_records(kind, rows):
|
||||
records = []
|
||||
for row in rows[1:]:
|
||||
if not row or not row[0].strip():
|
||||
continue
|
||||
cells = row + [""] * 8
|
||||
if kind == "sms":
|
||||
record = dict(zip(("timestamp", "orderType", "deposit_amount_str", "items_str",
|
||||
"previewText", "custName", "custPhone", "custAddress"), cells[:8]))
|
||||
record["previewText"] = record["previewText"].replace(" ", "\n")
|
||||
else:
|
||||
amount = cells[2].replace(",", "")
|
||||
record = {"timestamp": cells[0], "customer_name": cells[1],
|
||||
"total_amount": int(amount) if amount.lstrip("-").isdigit() else amount}
|
||||
record["_legacy_sheet_row"] = row
|
||||
records.append(normalize_record(kind, record))
|
||||
return records
|
||||
|
||||
|
||||
def merge_sheet_and_local(kind, rows, local_records):
|
||||
"""Match occurrences one-to-one; preserve unmatched rows and local-only saves."""
|
||||
local_by_time = defaultdict(list)
|
||||
normalized = [normalize_record(kind, item) for item in local_records]
|
||||
for index, record in enumerate(normalized):
|
||||
local_by_time[record["timestamp"]].append(index)
|
||||
used = set()
|
||||
result = []
|
||||
keys = (("orderType", "deposit_amount_str", "items_str", "previewText", "custName", "custPhone", "custAddress")
|
||||
if kind == "sms" else ("customer_name", "total_amount"))
|
||||
|
||||
def comparable(value, key):
|
||||
result = " ".join(str(value).split()) if value is not None else ""
|
||||
return result.replace(",", "") if key in {"deposit_amount_str", "total_amount"} else result
|
||||
|
||||
for record in sheet_records(kind, rows):
|
||||
candidates = local_by_time[record["timestamp"]]
|
||||
for index in candidates:
|
||||
local = normalized[index]
|
||||
if index in used or any(
|
||||
comparable(record.get(key), key) and comparable(local.get(key), key)
|
||||
and comparable(record.get(key), key) != comparable(local.get(key), key) for key in keys
|
||||
):
|
||||
continue
|
||||
merged = {**record, **local}
|
||||
for key, value in record.items():
|
||||
if not merged.get(key) and value:
|
||||
merged[key] = value
|
||||
record = normalize_record(kind, merged)
|
||||
used.add(index)
|
||||
break
|
||||
result.append(record)
|
||||
result.extend(record for index, record in enumerate(normalized) if index not in used)
|
||||
return result
|
||||
|
||||
|
||||
class PostgresHistoryStore:
|
||||
def __init__(self, db_config):
|
||||
self.database = PostgresSettingsStore(db_config)
|
||||
|
||||
def _connect(self):
|
||||
return self.database._connect()
|
||||
|
||||
@staticmethod
|
||||
def _create_tables(cursor):
|
||||
for table in TABLES.values():
|
||||
cursor.execute(sql.SQL("""
|
||||
CREATE TABLE IF NOT EXISTS {} (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
occurred_at TEXT NOT NULL,
|
||||
payload JSONB NOT NULL CHECK (jsonb_typeof(payload) = 'object'),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""").format(sql.Identifier(table)))
|
||||
cursor.execute(sql.SQL("CREATE INDEX IF NOT EXISTS {} ON {} (occurred_at text_pattern_ops)")
|
||||
.format(sql.Identifier(table + "_time_idx"), sql.Identifier(table)))
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS corm_history_imports (
|
||||
id SMALLINT PRIMARY KEY CHECK (id = 1), source TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
def check_ready(self):
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute("SELECT id FROM corm_history_imports WHERE id = 1")
|
||||
if cursor.fetchone() is None:
|
||||
raise SettingsNotInitialized("내역 DB 이전이 필요합니다. history_migrate.py를 실행해주세요.")
|
||||
for table in TABLES.values():
|
||||
cursor.execute(sql.SQL("SELECT id FROM {} LIMIT 0").format(sql.Identifier(table)))
|
||||
|
||||
def list_records(self, kind, day=None):
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
query = sql.SQL("SELECT id, payload FROM {} ").format(sql.Identifier(TABLES[kind]))
|
||||
parameters = ()
|
||||
if day is not None:
|
||||
query += sql.SQL("WHERE occurred_at LIKE %s ")
|
||||
parameters = (day + "%",)
|
||||
cursor.execute(query + sql.SQL("ORDER BY id"), parameters)
|
||||
return [{**payload, "id": record_id} for record_id, payload in cursor.fetchall()]
|
||||
|
||||
def add(self, kind, data):
|
||||
record = normalize_record(kind, data)
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql.SQL("INSERT INTO {} (occurred_at, payload) VALUES (%s, %s) RETURNING id")
|
||||
.format(sql.Identifier(TABLES[kind])), (record["timestamp"], Json(record)))
|
||||
return cursor.fetchone()[0]
|
||||
|
||||
def get_manual(self, record_id):
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute("SELECT payload FROM corm_manual_history WHERE id = %s", (record_id,))
|
||||
record = cursor.fetchone()
|
||||
return record[0] if record else None
|
||||
|
||||
def manual_timestamp_count(self, timestamp):
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute("SELECT count(*) FROM corm_manual_history WHERE occurred_at = %s", (timestamp,))
|
||||
return cursor.fetchone()[0]
|
||||
|
||||
def delete(self, kind, record_id):
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql.SQL("DELETE FROM {} WHERE id = %s RETURNING id")
|
||||
.format(sql.Identifier(TABLES[kind])), (record_id,))
|
||||
return cursor.fetchone() is not None
|
||||
|
||||
def clear_sms(self):
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute("DELETE FROM corm_sms_history")
|
||||
|
||||
def export_all(self):
|
||||
# One repeatable-read transaction gives both tables the same snapshot.
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
cursor.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
||||
result = {"kind": "corm-history"}
|
||||
for kind, table in TABLES.items():
|
||||
cursor.execute(sql.SQL("SELECT payload FROM {} ORDER BY id").format(sql.Identifier(table)))
|
||||
result[kind] = [row[0] for row in cursor.fetchall()]
|
||||
return result
|
||||
|
||||
def import_all(self, bundle, source):
|
||||
records = validate_bundle(bundle)
|
||||
with closing(self._connect()) as connection, connection, connection.cursor() as cursor:
|
||||
self._create_tables(cursor)
|
||||
cursor.execute("LOCK TABLE corm_sms_history, corm_manual_history, corm_history_imports IN EXCLUSIVE MODE")
|
||||
for table in (*TABLES.values(), "corm_history_imports"):
|
||||
cursor.execute(sql.SQL("SELECT EXISTS (SELECT 1 FROM {})").format(sql.Identifier(table)))
|
||||
if cursor.fetchone()[0]:
|
||||
raise SettingsAlreadyInitialized("이미 DB 내역이 있습니다. 기존 내역을 덮어쓰지 않았습니다.")
|
||||
for kind, table in TABLES.items():
|
||||
if records[kind]:
|
||||
execute_values(cursor, sql.SQL("INSERT INTO {} (occurred_at, payload) VALUES %s")
|
||||
.format(sql.Identifier(table)),
|
||||
[(record["timestamp"], Json(record)) for record in records[kind]])
|
||||
cursor.execute(sql.SQL("SELECT payload FROM {} ORDER BY id").format(sql.Identifier(table)))
|
||||
if [row[0] for row in cursor.fetchall()] != records[kind]:
|
||||
raise RuntimeError("내역 이전 검증 실패. 트랜잭션을 취소합니다.")
|
||||
cursor.execute("INSERT INTO corm_history_imports (id, source) VALUES (1, %s)", (source,))
|
||||
|
||||
|
||||
def validate_bundle(bundle):
|
||||
if not isinstance(bundle, dict) or bundle.get("kind") != "corm-history":
|
||||
raise ValueError("CORM 내역 백업이 필요합니다.")
|
||||
if not all(isinstance(bundle.get(kind), list) for kind in TABLES):
|
||||
raise ValueError("문자내역과 수동발주내역 목록이 필요합니다.")
|
||||
return {kind: [normalize_record(kind, item) for item in bundle[kind]] for kind in TABLES}
|
||||
@@ -9,7 +9,7 @@ import re
|
||||
import io
|
||||
import math
|
||||
import datetime
|
||||
import configparser
|
||||
import functools
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import uuid
|
||||
@@ -29,12 +29,18 @@ from naver_api import get_access_token, get_payment_done_orders, get_product_ord
|
||||
import cafe24_api
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional, Dict, Any
|
||||
from google_runtime import (
|
||||
GOOGLE_READ_TIMEOUT, GoogleTimeoutSession, SettingsCache,
|
||||
create_google_client, google_worker, history_access, run_google_io, settings_update,
|
||||
create_google_client, google_worker, history_access as google_history_access, run_google_io, settings_update,
|
||||
)
|
||||
from settings_store import (
|
||||
PostgresSettingsStore, SettingsConflict, SettingsNotInitialized,
|
||||
config_to_rows, rows_to_config, settings_db_config,
|
||||
)
|
||||
from history_store import PostgresHistoryStore
|
||||
|
||||
# ==========================================
|
||||
# SSO / 서브경로 호스팅 설정
|
||||
@@ -58,6 +64,15 @@ DB_CONFIG = {
|
||||
'user': _PG_USER,
|
||||
'password': _PG_PASSWORD,
|
||||
}
|
||||
SETTINGS_BACKEND = os.getenv("SETTINGS_BACKEND", "google").strip().lower()
|
||||
if SETTINGS_BACKEND not in {"google", "postgres"}:
|
||||
raise RuntimeError("SETTINGS_BACKEND는 google 또는 postgres여야 합니다.")
|
||||
SETTINGS_DB_CONFIG = settings_db_config()
|
||||
_postgres_settings = PostgresSettingsStore(SETTINGS_DB_CONFIG)
|
||||
HISTORY_BACKEND = os.getenv("HISTORY_BACKEND", "google").strip().lower()
|
||||
if HISTORY_BACKEND not in {"google", "postgres"}:
|
||||
raise RuntimeError("HISTORY_BACKEND는 google 또는 postgres여야 합니다.")
|
||||
_postgres_history = PostgresHistoryStore(SETTINGS_DB_CONFIG)
|
||||
|
||||
# 2. 반품 데이터 저장용 DB
|
||||
RETURN_DB_CONFIG = {
|
||||
@@ -193,9 +208,58 @@ def _load_settings_rows():
|
||||
return get_settings_worksheet().get_all_values()
|
||||
|
||||
|
||||
def settings_worker(function):
|
||||
"""DB settings must remain available even when Google workers are saturated."""
|
||||
@functools.wraps(function)
|
||||
async def wrapped(*args, **kwargs):
|
||||
if SETTINGS_BACKEND == "postgres":
|
||||
return await run_in_threadpool(function, *args, **kwargs)
|
||||
return await run_google_io(function, *args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
def history_worker(function):
|
||||
@functools.wraps(function)
|
||||
async def wrapped(*args, **kwargs):
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
return await run_in_threadpool(function, *args, **kwargs)
|
||||
return await run_google_io(function, *args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
def history_access(function):
|
||||
legacy = google_history_access(function)
|
||||
|
||||
@functools.wraps(function)
|
||||
def wrapped(*args, **kwargs):
|
||||
# DB records use stable IDs and DB transactions, so a slow Google order
|
||||
# cancellation must not hold up unrelated history reads and saves.
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
return function(*args, **kwargs)
|
||||
return legacy(*args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
def history_db_call(method, *args, **kwargs):
|
||||
try:
|
||||
return getattr(_postgres_history, method)(*args, **kwargs)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="내역의 일시와 입력 내용을 확인해주세요.") from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="DB 내역 처리를 확인하지 못했습니다. 새로고침하여 확인해주세요.") from exc
|
||||
|
||||
|
||||
def read_config(force_refresh=False):
|
||||
config = configparser.ConfigParser(allow_no_value=True)
|
||||
config.optionxform = str
|
||||
if SETTINGS_BACKEND == "postgres":
|
||||
try:
|
||||
rows, version = _postgres_settings.read()
|
||||
config = rows_to_config(rows)
|
||||
config._settings_version = version
|
||||
return config
|
||||
except SettingsNotInitialized as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="DB에서 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.") from exc
|
||||
|
||||
try:
|
||||
rows = _settings_cache.read(_load_settings_rows, force=force_refresh)
|
||||
@@ -205,44 +269,23 @@ def read_config(force_refresh=False):
|
||||
detail="구글에서 최신 설정을 읽지 못했습니다. 잠시 후 다시 시도해주세요.",
|
||||
) from exc
|
||||
|
||||
if rows and len(rows) > 1:
|
||||
for row in rows:
|
||||
if not row or not row[0].strip():
|
||||
continue
|
||||
section = row[0].strip()
|
||||
if section == "대분류 (Section)":
|
||||
continue
|
||||
|
||||
key = row[1].strip() if len(row) > 1 else ""
|
||||
|
||||
c_cells = [x.strip() for x in row[2:]]
|
||||
while c_cells and not c_cells[-1]:
|
||||
c_cells.pop()
|
||||
val = " | ".join(c_cells)
|
||||
|
||||
if not config.has_section(section):
|
||||
config.add_section(section)
|
||||
|
||||
if key:
|
||||
if val:
|
||||
config.set(section, key, val)
|
||||
else:
|
||||
config.set(section, key)
|
||||
return config
|
||||
return rows_to_config(rows)
|
||||
|
||||
def write_config(config):
|
||||
rows = [["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]]
|
||||
for section in config.sections():
|
||||
items = config.items(section)
|
||||
if not items:
|
||||
rows.append([section, "", ""])
|
||||
else:
|
||||
for k, v in items:
|
||||
if v is None:
|
||||
rows.append([section, k])
|
||||
else:
|
||||
v_parts = [p.strip() for p in v.split("|")]
|
||||
rows.append([section, k] + v_parts)
|
||||
rows = config_to_rows(config)
|
||||
if SETTINGS_BACKEND == "postgres":
|
||||
try:
|
||||
config._settings_version = _postgres_settings.write(
|
||||
rows, getattr(config, "_settings_version", None),
|
||||
)
|
||||
except SettingsConflict as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="DB 설정 저장을 확인하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.",
|
||||
) from exc
|
||||
return
|
||||
|
||||
try:
|
||||
ws = get_settings_worksheet()
|
||||
@@ -298,7 +341,9 @@ async def index(request: Request):
|
||||
|
||||
@app.get("/api/config")
|
||||
async def get_config():
|
||||
if _settings_cache.has_value:
|
||||
if SETTINGS_BACKEND == "postgres":
|
||||
config = await run_in_threadpool(read_config)
|
||||
elif _settings_cache.has_value:
|
||||
config = read_config()
|
||||
else:
|
||||
config = await run_google_io(read_config)
|
||||
@@ -307,7 +352,8 @@ async def get_config():
|
||||
data[section] = dict(config.items(section))
|
||||
data[section]["__order"] = list(config.options(section))
|
||||
return JSONResponse(data, headers={
|
||||
"X-Settings-Cache": "stale" if _settings_cache.stale else "fresh",
|
||||
"X-Settings-Cache": "none" if SETTINGS_BACKEND == "postgres" else ("stale" if _settings_cache.stale else "fresh"),
|
||||
"X-Settings-Backend": SETTINGS_BACKEND,
|
||||
})
|
||||
|
||||
|
||||
@@ -337,7 +383,7 @@ class SubgroupNamePayload(BaseModel):
|
||||
name: str = ""
|
||||
|
||||
@app.post("/api/products/settings")
|
||||
@google_worker
|
||||
@settings_worker
|
||||
@settings_update
|
||||
def save_products_settings(payload: ProductsPayload):
|
||||
config = read_config(force_refresh=True)
|
||||
@@ -377,7 +423,7 @@ def save_products_settings(payload: ProductsPayload):
|
||||
return {"status": "success"}
|
||||
|
||||
@app.post("/api/products/subgroup-name")
|
||||
@google_worker
|
||||
@settings_worker
|
||||
@settings_update
|
||||
def save_product_subgroup_name(payload: SubgroupNamePayload):
|
||||
group_key = payload.group_key.strip()
|
||||
@@ -527,11 +573,16 @@ async def startup_event():
|
||||
print(f"[Warning] DB 초기화 실패. CONTINUE_WITHOUT_DB=1 이므로 서버는 계속 시작합니다: {e}")
|
||||
else:
|
||||
raise
|
||||
if env_bool("SKIP_GOOGLE_INIT", False):
|
||||
if SETTINGS_BACKEND == "postgres":
|
||||
# Fail visibly on incomplete migration instead of falling back to old sheet values.
|
||||
await run_in_threadpool(_postgres_settings.read)
|
||||
elif env_bool("SKIP_GOOGLE_INIT", False):
|
||||
print("SKIP_GOOGLE_INIT=1 이므로 구글 시트 선초기화를 건너뜁니다.")
|
||||
else:
|
||||
# Google unavailability must not delay startup or the DB-backed tabs.
|
||||
_settings_cache.refresh_in_background(_load_settings_rows)
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
await run_in_threadpool(_postgres_history.check_ready)
|
||||
|
||||
@app.post("/api/order/submit")
|
||||
@google_worker
|
||||
@@ -660,9 +711,11 @@ def download_and_clear_sheet():
|
||||
|
||||
|
||||
@app.get("/api/sms/history")
|
||||
@google_worker
|
||||
@history_worker
|
||||
@history_access
|
||||
def get_history():
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
return history_db_call("list_records", "sms")
|
||||
local_history = {}
|
||||
def merge_history_item(sheet_item, local_item):
|
||||
if not local_item:
|
||||
@@ -727,9 +780,11 @@ def get_history():
|
||||
return []
|
||||
|
||||
@app.post("/api/sms/history")
|
||||
@google_worker
|
||||
@history_worker
|
||||
@history_access
|
||||
def add_history(data: dict):
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
return {"status": "success", "id": history_db_call("add", "sms", data)}
|
||||
with open(SMS_HISTORY_FILE, 'a', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
f.write('\n')
|
||||
@@ -768,9 +823,12 @@ def add_history(data: dict):
|
||||
return {"status": "success"}
|
||||
|
||||
@app.delete("/api/sms/history")
|
||||
@google_worker
|
||||
@history_worker
|
||||
@history_access
|
||||
def clear_history():
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
history_db_call("clear_sms")
|
||||
return {"status": "success"}
|
||||
if os.path.exists(SMS_HISTORY_FILE):
|
||||
os.remove(SMS_HISTORY_FILE)
|
||||
|
||||
@@ -782,10 +840,23 @@ def clear_history():
|
||||
|
||||
return {"status": "success"}
|
||||
|
||||
@app.delete("/api/sms/history/records/{record_id}")
|
||||
@history_worker
|
||||
@history_access
|
||||
def delete_sms_history_record(record_id: int):
|
||||
if HISTORY_BACKEND != "postgres":
|
||||
raise HTTPException(status_code=409, detail="내역 화면을 새로고침해주세요.")
|
||||
if not history_db_call("delete", "sms", record_id):
|
||||
raise HTTPException(status_code=404, detail="이미 삭제된 내역입니다. 새로고침해주세요.")
|
||||
return {"status": "success"}
|
||||
|
||||
|
||||
@app.delete("/api/sms/history/{index}")
|
||||
@google_worker
|
||||
@history_worker
|
||||
@history_access
|
||||
def delete_history_item(index: int):
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
raise HTTPException(status_code=409, detail="내역 화면을 새로고침한 후 다시 삭제해주세요.")
|
||||
try:
|
||||
ws = get_sms_history_worksheet()
|
||||
rows = ws.get_all_values()
|
||||
@@ -820,11 +891,13 @@ def delete_history_item(index: int):
|
||||
import sys
|
||||
|
||||
@app.get("/api/manual/history")
|
||||
@google_worker
|
||||
@history_worker
|
||||
@history_access
|
||||
def get_manual_history():
|
||||
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
|
||||
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
return history_db_call("list_records", "manual", day=today_prefix)
|
||||
|
||||
local_history = {}
|
||||
if os.path.exists(MANUAL_HISTORY_FILE):
|
||||
@@ -868,9 +941,11 @@ def get_manual_history():
|
||||
return list(local_history.values())
|
||||
|
||||
@app.post("/api/manual/history")
|
||||
@google_worker
|
||||
@history_worker
|
||||
@history_access
|
||||
def add_manual_history(data: dict):
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
return {"status": "success", "id": history_db_call("add", "manual", data)}
|
||||
local_history = []
|
||||
korea_tz = datetime.timezone(datetime.timedelta(hours=9))
|
||||
today_prefix = datetime.datetime.now(korea_tz).strftime("%Y-%m-%d")
|
||||
@@ -906,10 +981,43 @@ def add_manual_history(data: dict):
|
||||
|
||||
return {"status": "success"}
|
||||
|
||||
def delete_manual_order_rows(timestamp):
|
||||
"""Keep cancellation of the active Google order queue, separate from history."""
|
||||
ws = get_manual_worksheet()
|
||||
rows = ws.get_all_values()
|
||||
# Delete exact matching rows in one request, from bottom to top.
|
||||
requests = [{"deleteDimension": {"range": {
|
||||
"sheetId": ws.id, "dimension": "ROWS", "startIndex": index, "endIndex": index + 1,
|
||||
}}} for index in reversed(range(1, len(rows))) if rows[index] and rows[index][0] == timestamp]
|
||||
if requests:
|
||||
ws.spreadsheet.batch_update({"requests": requests})
|
||||
|
||||
|
||||
@app.delete("/api/manual/history/records/{record_id}")
|
||||
@google_worker
|
||||
@google_history_access
|
||||
def delete_manual_history_record(record_id: int):
|
||||
if HISTORY_BACKEND != "postgres":
|
||||
raise HTTPException(status_code=409, detail="내역 화면을 새로고침해주세요.")
|
||||
record = history_db_call("get_manual", record_id)
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail="이미 삭제된 내역입니다. 새로고침해주세요.")
|
||||
if history_db_call("manual_timestamp_count", record["timestamp"]) > 1:
|
||||
raise HTTPException(status_code=409, detail="같은 일시의 수동발주가 여러 건입니다. 발주 시트에서 대상 주문을 먼저 확인해주세요.")
|
||||
try:
|
||||
delete_manual_order_rows(record["timestamp"])
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="발주 시트 삭제를 확인하지 못했습니다. 내역을 보존했습니다. 발주 시트 확인 후 다시 시도해주세요.") from exc
|
||||
history_db_call("delete", "manual", record_id)
|
||||
return {"status": "success"}
|
||||
|
||||
|
||||
@app.delete("/api/manual/history/{timestamp}")
|
||||
@google_worker
|
||||
@history_access
|
||||
def delete_manual_history(timestamp: str):
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
raise HTTPException(status_code=409, detail="내역 화면을 새로고침한 후 다시 삭제해주세요.")
|
||||
# 구글 시트에서 삭제
|
||||
try:
|
||||
ws = get_manual_worksheet()
|
||||
@@ -980,7 +1088,7 @@ async def get_fonts():
|
||||
return fonts_list
|
||||
|
||||
@app.post("/api/gift/settings")
|
||||
@google_worker
|
||||
@settings_worker
|
||||
@settings_update
|
||||
def save_gift_settings(payload: dict):
|
||||
# 하위 호환성 (기존 rules만 오는 경우)
|
||||
@@ -1016,7 +1124,7 @@ def save_gift_settings(payload: dict):
|
||||
return {"status": "success"}
|
||||
|
||||
@app.post("/api/app/settings")
|
||||
@google_worker
|
||||
@settings_worker
|
||||
@settings_update
|
||||
def save_app_settings(payload: dict):
|
||||
config = read_config(force_refresh=True)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Explicit, one-time settings import. No Google writes or automatic overwrite."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from settings_store import (
|
||||
PostgresSettingsStore, SettingsAlreadyInitialized, SettingsNotInitialized,
|
||||
settings_db_config, validate_rows,
|
||||
)
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def fingerprint(rows):
|
||||
encoded = json.dumps(rows, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def save_snapshot(path, rows, source):
|
||||
target = Path(path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {"format": 1, "source": source, "sha256": fingerprint(rows), "rows": rows}
|
||||
# Never replace an existing backup. Restrict access on systems supporting POSIX modes.
|
||||
descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(payload, stream, ensure_ascii=False, indent=2)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def load_snapshot(path):
|
||||
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if payload.get("format") != 1 or payload.get("sha256") != fingerprint(payload["rows"]):
|
||||
raise ValueError("백업 파일 형식 또는 체크섬이 올바르지 않습니다.")
|
||||
validate_rows(payload["rows"])
|
||||
return payload["rows"], "backup-file"
|
||||
|
||||
|
||||
def read_google_rows():
|
||||
# Reuse the application's credential loading and bounded HTTP sessions.
|
||||
# Do not use get_settings_worksheet(): that helper creates a missing tab.
|
||||
import main
|
||||
worksheet = main.get_gspread_client().open_by_key(main.SETTINGS_SPREADSHEET_ID).worksheet("설정")
|
||||
return worksheet.get_all_values(), "google:" + main.SETTINGS_SPREADSHEET_ID + ":설정"
|
||||
|
||||
|
||||
def build_store():
|
||||
return PostgresSettingsStore(settings_db_config())
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
load_dotenv(BASE_DIR / ".env")
|
||||
parser = argparse.ArgumentParser(description="구글 시트 '설정' 탭 → PostgreSQL 이전 / 검증 / 백업")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
importer = commands.add_parser("import", help="기본은 읽기 전용 점검. --apply일 때만 DB에 저장")
|
||||
importer.add_argument("--apply", action="store_true")
|
||||
importer.add_argument("--backup", help="--apply 필수: 이전 전 원본을 보관할 새 JSON 경로")
|
||||
importer.add_argument("--input-file", help="구글 대신 이 도구가 만든 JSON 백업에서 읽기")
|
||||
verifier = commands.add_parser("verify", help="원본과 DB가 같은지 읽기 전용 검증")
|
||||
verifier.add_argument("--input-file")
|
||||
exporter = commands.add_parser("export", help="현재 DB 설정을 새 JSON 파일로 백업")
|
||||
exporter.add_argument("--output", required=True)
|
||||
args = parser.parse_args(argv)
|
||||
if args.command == "import" and args.apply and not args.backup:
|
||||
parser.error("--apply에는 --backup 경로가 필요합니다.")
|
||||
|
||||
try:
|
||||
if args.command == "export":
|
||||
rows, version = build_store().read()
|
||||
save_snapshot(args.output, rows, f"postgres:version:{version}")
|
||||
print(f"DB 설정 백업 완료 (version={version}, sha256={fingerprint(rows)}).")
|
||||
return 0
|
||||
|
||||
rows, source = load_snapshot(args.input_file) if args.input_file else read_google_rows()
|
||||
config = validate_rows(rows)
|
||||
print(f"원본 확인: {len(rows)}행 / {len(config.sections())}개 분류 / sha256={fingerprint(rows)}")
|
||||
if args.command == "verify":
|
||||
stored, version = build_store().read()
|
||||
if stored != rows:
|
||||
print("검증 실패: 원본과 DB 설정이 다릅니다. 전환 전에 차이를 확인해주세요.", file=sys.stderr)
|
||||
return 1
|
||||
print(f"원본과 DB 전체 행·셀·순서 일치 (version={version}).")
|
||||
elif args.apply:
|
||||
save_snapshot(args.backup, rows, source)
|
||||
version = build_store().import_rows(rows, source)
|
||||
print(f"DB 이전 및 트랜잭션 내 전체 데이터 검증 완료 (version={version}).")
|
||||
else:
|
||||
print("점검만 완료했습니다. DB·구글 시트에 쓰지 않았습니다.")
|
||||
return 0
|
||||
except (SettingsAlreadyInitialized, SettingsNotInitialized) as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
except Exception as exc:
|
||||
# Connection errors and parser errors may contain credentials or cell values.
|
||||
print(f"작업 실패 ({type(exc).__name__}). 접속 환경·원본·백업 경로를 확인해주세요.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Ordered application settings in PostgreSQL; credentials stay in the environment."""
|
||||
|
||||
import configparser
|
||||
import os
|
||||
from contextlib import closing
|
||||
|
||||
import psycopg2
|
||||
from psycopg2.extras import Json
|
||||
|
||||
|
||||
HEADER = ["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]
|
||||
|
||||
|
||||
def settings_db_config():
|
||||
"""Share server credentials, but never fall back to the item-code database."""
|
||||
return {
|
||||
"host": os.getenv("POSTGRES_HOST", "postgres-db"),
|
||||
"port": int(os.getenv("POSTGRES_PORT", "5432")),
|
||||
"dbname": os.getenv("SETTINGS_DB", "corm_db").strip() or "corm_db",
|
||||
"user": os.getenv("POSTGRES_USER", "king"),
|
||||
"password": os.getenv("POSTGRES_PASSWORD", ""),
|
||||
}
|
||||
|
||||
|
||||
class SettingsNotInitialized(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class SettingsConflict(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class SettingsAlreadyInitialized(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def rows_to_config(rows):
|
||||
config = configparser.ConfigParser(allow_no_value=True)
|
||||
config.optionxform = str
|
||||
for row in rows:
|
||||
if not row or not row[0].strip():
|
||||
continue
|
||||
section = row[0].strip()
|
||||
if section == HEADER[0]:
|
||||
continue
|
||||
key = row[1].strip() if len(row) > 1 else ""
|
||||
cells = [cell.strip() for cell in row[2:]]
|
||||
while cells and not cells[-1]:
|
||||
cells.pop()
|
||||
if not config.has_section(section):
|
||||
config.add_section(section)
|
||||
if key:
|
||||
config.set(section, key, " | ".join(cells) or None)
|
||||
return config
|
||||
|
||||
|
||||
def config_to_rows(config):
|
||||
rows = [HEADER.copy()]
|
||||
for section in config.sections():
|
||||
items = config.items(section)
|
||||
if not items:
|
||||
rows.append([section, "", ""])
|
||||
for key, value in items:
|
||||
rows.append([section, key] if value is None else
|
||||
[section, key] + [part.strip() for part in value.split("|")])
|
||||
return rows
|
||||
|
||||
|
||||
def validate_rows(rows):
|
||||
if not isinstance(rows, list) or not rows or not all(
|
||||
isinstance(row, list) and all(isinstance(cell, str) and "\x00" not in cell for cell in row)
|
||||
for row in rows
|
||||
):
|
||||
raise ValueError("설정은 문자열 셀로 구성된 비어 있지 않은 행 배열이어야 합니다.")
|
||||
config = rows_to_config(rows)
|
||||
if not config.sections():
|
||||
raise ValueError("이전할 설정이 없습니다. 원본의 '설정' 탭을 확인해주세요.")
|
||||
# Also validate interpolation before committing, as the existing API uses items().
|
||||
config_to_rows(config)
|
||||
return config
|
||||
|
||||
|
||||
class PostgresSettingsStore:
|
||||
def __init__(self, db_config):
|
||||
self.db_config = dict(db_config)
|
||||
|
||||
def _connect(self):
|
||||
return psycopg2.connect(
|
||||
**self.db_config, connect_timeout=3,
|
||||
options="-c statement_timeout=5000 -c lock_timeout=3000",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _create_table(cursor):
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS corm_settings (
|
||||
id SMALLINT PRIMARY KEY CHECK (id = 1),
|
||||
rows JSONB NOT NULL CHECK (jsonb_typeof(rows) = 'array'),
|
||||
version BIGINT NOT NULL DEFAULT 1 CHECK (version > 0),
|
||||
source TEXT NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
def read(self):
|
||||
with closing(self._connect()) as connection, connection:
|
||||
with connection.cursor() as cursor:
|
||||
try:
|
||||
cursor.execute("SELECT rows, version FROM corm_settings WHERE id = 1")
|
||||
except psycopg2.errors.UndefinedTable as exc:
|
||||
raise SettingsNotInitialized("설정 DB가 없습니다. 먼저 settings_migrate.py로 이전해주세요.") from exc
|
||||
record = cursor.fetchone()
|
||||
if record is None:
|
||||
raise SettingsNotInitialized("설정 DB가 비어 있습니다. 먼저 settings_migrate.py로 이전해주세요.")
|
||||
validate_rows(record[0])
|
||||
return record[0], record[1]
|
||||
|
||||
def write(self, rows, expected_version):
|
||||
validate_rows(rows)
|
||||
if not isinstance(expected_version, int) or expected_version < 1:
|
||||
raise SettingsConflict("설정을 다시 읽은 후 저장해주세요.")
|
||||
with closing(self._connect()) as connection, connection:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("""
|
||||
UPDATE corm_settings
|
||||
SET rows = %s, version = version + 1, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = 1 AND version = %s RETURNING version
|
||||
""", (Json(rows, dumps=_json_dumps), expected_version))
|
||||
record = cursor.fetchone()
|
||||
if record is None:
|
||||
raise SettingsConflict("다른 요청이 설정을 변경했습니다. 새로고침 후 다시 저장해주세요.")
|
||||
return record[0]
|
||||
|
||||
def import_rows(self, rows, source):
|
||||
"""Initialize once; DDL, insert and readback all share one transaction."""
|
||||
validate_rows(rows)
|
||||
with closing(self._connect()) as connection, connection:
|
||||
with connection.cursor() as cursor:
|
||||
self._create_table(cursor)
|
||||
cursor.execute("""
|
||||
INSERT INTO corm_settings (id, rows, source)
|
||||
VALUES (1, %s, %s) ON CONFLICT (id) DO NOTHING RETURNING version
|
||||
""", (Json(rows, dumps=_json_dumps), source))
|
||||
record = cursor.fetchone()
|
||||
if record is None:
|
||||
raise SettingsAlreadyInitialized("이미 DB 설정이 있습니다. 기존 설정을 덮어쓰지 않았습니다.")
|
||||
cursor.execute("SELECT rows FROM corm_settings WHERE id = 1")
|
||||
if cursor.fetchone()[0] != rows:
|
||||
raise RuntimeError("이전 후 설정 검증에 실패했습니다. 트랜잭션을 취소합니다.")
|
||||
return record[0]
|
||||
|
||||
|
||||
def _json_dumps(value):
|
||||
import json
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
+52
-30
@@ -19,6 +19,22 @@
|
||||
};
|
||||
})();
|
||||
|
||||
async function settingsErrorMessage(response) {
|
||||
const fallback = response.status === 409
|
||||
? '다른 요청이 설정을 변경했습니다. 새로고침 후 다시 저장해주세요.'
|
||||
: '설정을 저장하지 못했습니다. 새로고침하여 저장 여부를 확인해주세요.';
|
||||
const data = await response.json().catch(() => ({}));
|
||||
return typeof data.detail === 'string' ? data.detail : fallback;
|
||||
}
|
||||
|
||||
async function readHistoryResponse(response) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof data.detail === 'string' ? data.detail : '내역 처리를 확인하지 못했습니다. 새로고침해주세요.');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function showToast(message) {
|
||||
const toast = document.createElement('div');
|
||||
toast.textContent = message;
|
||||
@@ -1744,11 +1760,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(histData)
|
||||
}).then(() => {
|
||||
}).then(readHistoryResponse).then(() => {
|
||||
if (typeof loadManualHistory === 'function') {
|
||||
loadManualHistory();
|
||||
}
|
||||
});
|
||||
}).catch(error => alert('발주는 완료됐지만 수동발주내역 저장을 확인하지 못했습니다. ' + error.message));
|
||||
}
|
||||
|
||||
// Copy the same text that is written to the sheet remarks/comparison field.
|
||||
@@ -2176,14 +2192,14 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(histData)
|
||||
}).then(() => {
|
||||
}).then(readHistoryResponse).then(() => {
|
||||
writeSmsCustomerCache(stamp, {
|
||||
custName: custName,
|
||||
custPhone: custPhone,
|
||||
custAddress: custAddress
|
||||
});
|
||||
loadSmsHistory();
|
||||
});
|
||||
}).catch(error => alert('문자내역 저장을 확인하지 못했습니다. ' + error.message));
|
||||
|
||||
|
||||
});
|
||||
@@ -2194,14 +2210,14 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
function loadSmsHistory() {
|
||||
const u = document.getElementById('sms-history-list');
|
||||
u.innerHTML = '';
|
||||
fetch('/api/sms/history').then(r => r.json()).then(data => {
|
||||
fetch('/api/sms/history').then(readHistoryResponse).then(data => {
|
||||
data.slice().reverse().forEach((d, idx) => {
|
||||
const actualIdx = data.length - 1 - idx;
|
||||
const li = document.createElement('li');
|
||||
li.style.cursor = 'pointer';
|
||||
li.style.padding = '4px 0';
|
||||
li.style.borderBottom = '1px solid #eee';
|
||||
li.onclick = () => window.loadHistoryItem(actualIdx);
|
||||
li.onclick = () => window.loadHistoryItem(actualIdx, d.id);
|
||||
|
||||
const cachedCustomer = readSmsCustomerCache()[d.timestamp] || {};
|
||||
const name = firstNonEmpty(d.custName, d.customer_name, cachedCustomer.custName, cachedCustomer.customer_name);
|
||||
@@ -2226,7 +2242,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
spanDel.style.marginLeft = '8px';
|
||||
spanDel.title = '삭제';
|
||||
spanDel.textContent = '❌';
|
||||
spanDel.onclick = (e) => window.deleteHistory(actualIdx, e);
|
||||
spanDel.onclick = (e) => window.deleteHistory(actualIdx, e, d.id);
|
||||
li.appendChild(spanDel);
|
||||
|
||||
u.appendChild(li);
|
||||
@@ -2235,7 +2251,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
}).catch(error => { u.textContent = error.message; });
|
||||
}
|
||||
|
||||
const SMS_CUSTOMER_CACHE_KEY = 'smsCustomerHistoryByTimestamp';
|
||||
@@ -2268,7 +2284,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const u = document.getElementById('manual-history-list');
|
||||
if (!u) return;
|
||||
u.innerHTML = '';
|
||||
fetch('/api/manual/history').then(r => r.json()).then(data => {
|
||||
fetch('/api/manual/history').then(readHistoryResponse).then(data => {
|
||||
let totalCount = data.length;
|
||||
let totalAmount = 0;
|
||||
data.forEach((d) => {
|
||||
@@ -2306,18 +2322,21 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
spanDel.textContent = '❌';
|
||||
spanDel.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (confirm("🚨 [경고] 이 수동발주 기록을 삭제하시겠습니까?\n\n(구글 시트에서도 함께 삭제됩니다!)")) {
|
||||
if (confirm("이 수동발주 기록을 삭제하시겠습니까?\n\n연결된 발주 시트의 주문도 함께 삭제됩니다.")) {
|
||||
const btn = e.target;
|
||||
btn.textContent = '⏳';
|
||||
btn.style.pointerEvents = 'none';
|
||||
fetch(`/api/manual/history/${encodeURIComponent(d.timestamp)}`, { method: 'DELETE' })
|
||||
.then(() => {
|
||||
const deleteUrl = d.id !== undefined
|
||||
? `/api/manual/history/records/${d.id}`
|
||||
: `/api/manual/history/${encodeURIComponent(d.timestamp)}`;
|
||||
fetch(deleteUrl, { method: 'DELETE' })
|
||||
.then(readHistoryResponse).then(() => {
|
||||
window.loadManualHistory();
|
||||
const iframe = document.querySelector('#manual-tab iframe');
|
||||
if (iframe) iframe.src = iframe.src;
|
||||
})
|
||||
.catch(() => {
|
||||
alert("삭제 중 오류가 발생했습니다.");
|
||||
.catch(error => {
|
||||
alert(error.message || "삭제 중 오류가 발생했습니다.");
|
||||
btn.textContent = '❌';
|
||||
btn.style.pointerEvents = 'auto';
|
||||
});
|
||||
@@ -2327,13 +2346,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
u.appendChild(li);
|
||||
});
|
||||
}).catch(err => console.error("Error loading manual history", err));
|
||||
}).catch(error => { u.textContent = error.message; });
|
||||
}
|
||||
|
||||
window.loadHistoryItem = function (idx) {
|
||||
fetch('/api/sms/history').then(r => r.json()).then(data => {
|
||||
if (idx < 0 || idx >= data.length) return;
|
||||
const d = data[idx];
|
||||
window.loadHistoryItem = function (idx, recordId) {
|
||||
fetch('/api/sms/history').then(readHistoryResponse).then(data => {
|
||||
const d = recordId !== undefined ? data.find(record => record.id === recordId) : data[idx];
|
||||
if (!d) { loadSmsHistory(); return; }
|
||||
|
||||
document.getElementById('btn-reset').click();
|
||||
|
||||
@@ -2428,19 +2447,22 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
updateSelectedOrderItemsSummary();
|
||||
|
||||
|
||||
});
|
||||
}).catch(error => alert(error.message));
|
||||
}
|
||||
|
||||
window.deleteHistory = function (idx, e) {
|
||||
window.deleteHistory = function (idx, e, recordId) {
|
||||
e.stopPropagation();
|
||||
if (confirm("이 기록을 삭제하시겠습니까?")) {
|
||||
fetch(`/api/sms/history/${idx}`, { method: 'DELETE' }).then(() => loadSmsHistory());
|
||||
const url = recordId !== undefined ? `/api/sms/history/records/${recordId}` : `/api/sms/history/${idx}`;
|
||||
fetch(url, { method: 'DELETE' }).then(readHistoryResponse)
|
||||
.then(() => loadSmsHistory()).catch(error => alert(error.message));
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('btn-sms-clear-all').addEventListener('click', () => {
|
||||
if (confirm("정말로 모든 기록을 삭제하시겠습니까?")) {
|
||||
fetch('/api/sms/history', { method: 'DELETE' }).then(() => loadSmsHistory());
|
||||
fetch('/api/sms/history', { method: 'DELETE' }).then(readHistoryResponse)
|
||||
.then(() => loadSmsHistory()).catch(error => alert(error.message));
|
||||
}
|
||||
|
||||
|
||||
@@ -2620,7 +2642,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
buildProductTab(configData);
|
||||
});
|
||||
} else {
|
||||
alert('저장 실패');
|
||||
alert(await settingsErrorMessage(res));
|
||||
}
|
||||
} catch (e) {
|
||||
alert('오류 발생');
|
||||
@@ -2717,7 +2739,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
body: JSON.stringify({ [BULK_TRACKING_PREFIX_SETTING]: prefix })
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Failed to save bulk tracking prefix');
|
||||
if (!res.ok) throw new Error(await settingsErrorMessage(res));
|
||||
if (!configData.APP_SETTINGS) configData.APP_SETTINGS = {};
|
||||
configData.APP_SETTINGS[BULK_TRACKING_PREFIX_SETTING] = prefix;
|
||||
if (btnBulkPrefixSave) btnBulkPrefixSave.style.backgroundColor = '#4a5568';
|
||||
@@ -2755,7 +2777,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
await saveBulkTrackingPrefix();
|
||||
} catch (err) {
|
||||
console.error('Bulk prefix save failed:', err);
|
||||
alert('송장 앞 숫자 저장에 실패했습니다.');
|
||||
alert(err.message || '송장 앞 숫자 저장에 실패했습니다.');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2788,7 +2810,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
savedPrefix = await saveBulkTrackingPrefix({ silent: true });
|
||||
} catch (err) {
|
||||
console.error('Bulk prefix save failed:', err);
|
||||
alert('송장 앞 숫자 저장에 실패했습니다.');
|
||||
alert(err.message || '송장 앞 숫자 저장에 실패했습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3518,8 +3540,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
}).then(r => {
|
||||
if (!r.ok) throw new Error("Network response was not ok (status " + r.status + ")");
|
||||
}).then(async r => {
|
||||
if (!r.ok) throw new Error(await settingsErrorMessage(r));
|
||||
return r.json();
|
||||
}).then(res => {
|
||||
alert("상품 설정이 저장되었습니다.");
|
||||
@@ -3538,7 +3560,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
});
|
||||
}).catch(err => {
|
||||
console.error(err);
|
||||
alert("저장 실패!");
|
||||
alert(err.message || "저장 실패!");
|
||||
document.getElementById('btn-product-save').innerText = '상품 설정 저장';
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Validate operator deployment decisions without production access."""
|
||||
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import deploy_corm as deployment
|
||||
from history_store import normalize_record
|
||||
from settings_store import HEADER, SettingsNotInitialized
|
||||
|
||||
|
||||
ROWS = [HEADER, ["APP_SETTINGS", "shipping_fee", "3500"]]
|
||||
HISTORY = {"kind": "corm-history", "sms": [], "manual": []}
|
||||
|
||||
|
||||
class DeploymentTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.output = io.StringIO()
|
||||
|
||||
def test_environment_switch_preserves_existing_secret_and_database_keys(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / ".env"
|
||||
path.write_text("POSTGRES_PASSWORD='keep-$-secret'\nITEMCODE_DB=itemcode_db\n# preserve comment\n", encoding="utf-8")
|
||||
with patch.object(os, "chown", create=True), redirect_stdout(self.output):
|
||||
deployment.switch_environment(path)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
self.assertIn("POSTGRES_PASSWORD='keep-$-secret'", text)
|
||||
self.assertIn("ITEMCODE_DB=itemcode_db", text)
|
||||
self.assertIn("# preserve comment", text)
|
||||
self.assertIn("SETTINGS_DB=corm_db", text)
|
||||
self.assertIn("HISTORY_BACKEND=postgres", text)
|
||||
|
||||
def test_existing_settings_difference_is_never_overwritten(self):
|
||||
store = MagicMock()
|
||||
store.read.return_value = ([HEADER, ["APP_SETTINGS", "shipping_fee", "9999"]], 2)
|
||||
with patch.object(deployment, "load_snapshot", return_value=(ROWS, "test")), \
|
||||
patch.object(deployment, "load_backup", return_value=(HISTORY, "test")), \
|
||||
patch.object(deployment, "PostgresSettingsStore", return_value=store), \
|
||||
self.assertRaises(RuntimeError):
|
||||
deployment.migrate("unused")
|
||||
store.import_rows.assert_not_called()
|
||||
|
||||
def test_incomplete_import_can_resume_without_reimporting_settings(self):
|
||||
settings = MagicMock()
|
||||
settings.read.return_value = (ROWS, 1)
|
||||
histories = MagicMock()
|
||||
histories.check_ready.side_effect = SettingsNotInitialized()
|
||||
histories.export_all.return_value = HISTORY
|
||||
with patch.object(deployment, "load_snapshot", return_value=(ROWS, "test")), \
|
||||
patch.object(deployment, "load_backup", return_value=(HISTORY, "test")), \
|
||||
patch.object(deployment, "PostgresSettingsStore", return_value=settings), \
|
||||
patch.object(deployment, "PostgresHistoryStore", return_value=histories), redirect_stdout(self.output):
|
||||
deployment.migrate("unused")
|
||||
settings.import_rows.assert_not_called()
|
||||
histories.import_all.assert_called_once_with(HISTORY, "test")
|
||||
|
||||
def test_snapshot_uses_existing_database_when_already_converted(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
settings = MagicMock()
|
||||
settings.read.return_value = (ROWS, 1)
|
||||
histories = MagicMock()
|
||||
histories.export_all.return_value = HISTORY
|
||||
with patch.object(deployment, "PostgresSettingsStore", return_value=settings), \
|
||||
patch.object(deployment, "PostgresHistoryStore", return_value=histories), \
|
||||
patch.object(deployment, "read_google_rows") as google, \
|
||||
patch.object(os, "chown", create=True), redirect_stdout(self.output):
|
||||
deployment.snapshot(directory, "postgres", "postgres")
|
||||
google.assert_not_called()
|
||||
self.assertTrue((Path(directory) / "settings-source.json").exists())
|
||||
self.assertTrue((Path(directory) / "history-source.json").exists())
|
||||
|
||||
def test_database_creation_does_not_modify_an_existing_database(self):
|
||||
connection = MagicMock()
|
||||
cursor = connection.cursor.return_value.__enter__.return_value
|
||||
cursor.fetchone.return_value = (1,)
|
||||
with patch.object(deployment, "settings_db_config", return_value={"dbname": "corm_db", "user": "app"}), \
|
||||
patch.object(deployment.psycopg2, "connect", return_value=connection), redirect_stdout(self.output):
|
||||
deployment.ensure_database()
|
||||
cursor.execute.assert_called_once()
|
||||
|
||||
def test_deployment_error_output_does_not_reveal_credentials(self):
|
||||
with patch.object(deployment, "ensure_database", side_effect=RuntimeError("password=do-not-print")), \
|
||||
redirect_stderr(self.output):
|
||||
self.assertEqual(deployment.main(["database"]), 1)
|
||||
self.assertNotIn("do-not-print", self.output.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -165,6 +165,13 @@ class TimeoutTests(unittest.TestCase):
|
||||
|
||||
class ApiTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
# These tests exercise the legacy Google backend regardless of local .env.
|
||||
backend = patch.object(main, "SETTINGS_BACKEND", "google")
|
||||
backend.start()
|
||||
self.addCleanup(backend.stop)
|
||||
histories = patch.object(main, "HISTORY_BACKEND", "google")
|
||||
histories.start()
|
||||
self.addCleanup(histories.stop)
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.cache = runtime.SettingsCache(Path(self.directory.name) / "settings.json", "test")
|
||||
self.cache_patch = patch.object(main, "_settings_cache", self.cache)
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""History fidelity, stable deletion, database failures and migration safeguards."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import datetime
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import main
|
||||
import history_migrate as migration
|
||||
import history_store
|
||||
from history_store import PostgresHistoryStore, merge_sheet_and_local, normalize_record, validate_bundle
|
||||
from settings_store import SettingsAlreadyInitialized
|
||||
from test_google_resilience import request
|
||||
|
||||
|
||||
READ_SOURCE = migration.read_source
|
||||
STAMP = "2026-10-22 11:22:33"
|
||||
SMS = {"timestamp": STAMP, "orderType": "normal", "deposit_amount_str": "3,500원",
|
||||
"custName": "테스트 고객", "custPhone": "010-0000-0000", "custAddress": "테스트 주소",
|
||||
"items": [{"label": "상품", "code": "TEST-1", "qty": 2}],
|
||||
"smsOpts": {"discount": True, "pointDeduction": 500}, "previewText": "첫줄\n둘째줄"}
|
||||
SMS_ROWS = [["일시", "주문유형", "입금액", "주문아이템", "메시지", "이름", "연락처", "주소"],
|
||||
[STAMP, "normal", "3,500원", "상품[TEST-1] 2개", "첫줄 둘째줄", "테스트 고객", "010-0000-0000", "테스트 주소"]]
|
||||
MANUAL = {"timestamp": STAMP, "customer_name": "테스트 고객", "total_amount": 3500}
|
||||
BUNDLE = {"kind": "corm-history", "sms": [SMS], "manual": [MANUAL]}
|
||||
|
||||
|
||||
class MergeTests(unittest.TestCase):
|
||||
def test_sheet_and_local_details_are_merged_without_duplicates(self):
|
||||
records = merge_sheet_and_local("sms", SMS_ROWS, [SMS])
|
||||
self.assertEqual(len(records), 1)
|
||||
self.assertEqual(records[0]["items"], SMS["items"])
|
||||
self.assertEqual(records[0]["smsOpts"], SMS["smsOpts"])
|
||||
self.assertEqual(records[0]["custAddress"], SMS["custAddress"])
|
||||
self.assertEqual(records[0]["previewText"], SMS["previewText"])
|
||||
self.assertEqual(records[0]["_legacy_sheet_row"], SMS_ROWS[1])
|
||||
|
||||
def test_duplicate_timestamps_and_local_only_records_are_preserved(self):
|
||||
local_only = {**SMS, "timestamp": "2026-10-22 11:22:34"}
|
||||
rows = SMS_ROWS + [SMS_ROWS[1].copy()]
|
||||
records = merge_sheet_and_local("sms", rows, [SMS, copy.deepcopy(SMS), local_only])
|
||||
self.assertEqual(len(records), 3)
|
||||
self.assertEqual([r["timestamp"] for r in records], [STAMP, STAMP, local_only["timestamp"]])
|
||||
|
||||
def test_distinct_orders_at_same_time_are_not_collapsed(self):
|
||||
other = {**SMS, "custName": "다른 고객"}
|
||||
records = merge_sheet_and_local("sms", SMS_ROWS, [other, SMS])
|
||||
self.assertEqual(len(records), 2)
|
||||
self.assertEqual([r["custName"] for r in records], ["테스트 고객", "다른 고객"])
|
||||
|
||||
def test_manual_historical_rows_and_text_amounts_are_kept(self):
|
||||
rows = [["일시", "이름", "금액"], ["2020-01-01 12:00:00", "과거", "누락"],
|
||||
[STAMP, "테스트 고객", "3,500", "추가 열"]]
|
||||
records = merge_sheet_and_local("manual", rows, [MANUAL])
|
||||
self.assertEqual(len(records), 2)
|
||||
self.assertEqual(records[0]["total_amount"], "누락")
|
||||
self.assertEqual(records[1]["total_amount"], 3500)
|
||||
self.assertEqual(records[1]["_legacy_sheet_row"][-1], "추가 열")
|
||||
|
||||
def test_invalid_records_fail_instead_of_disappearing(self):
|
||||
for value in ({}, {"timestamp": ""}, [], {"timestamp": STAMP, "amount": float("nan")}):
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
normalize_record("manual", value)
|
||||
with self.assertRaises(ValueError):
|
||||
validate_bundle({"kind": "settings", "sms": [], "manual": []})
|
||||
|
||||
|
||||
class HistoryApiTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
self.store = MagicMock()
|
||||
self.store.list_records.return_value = [{**SMS, "id": 42}]
|
||||
self.store.add.return_value = 42
|
||||
self.store.delete.return_value = True
|
||||
self.store.get_manual.return_value = MANUAL.copy()
|
||||
self.store.manual_timestamp_count.return_value = 1
|
||||
for name, value in (("HISTORY_BACKEND", "postgres"), ("_postgres_history", self.store)):
|
||||
mocked = patch.object(main, name, value)
|
||||
mocked.start()
|
||||
self.addCleanup(mocked.stop)
|
||||
self.google_mock = patch.object(main, "get_sms_history_worksheet", side_effect=AssertionError("Unexpected sheet history I/O"))
|
||||
self.google_mock.start()
|
||||
self.addCleanup(self.google_mock.stop)
|
||||
self.local_file = patch("builtins.open", side_effect=AssertionError("Unexpected local history I/O"))
|
||||
self.local_file.start()
|
||||
self.addCleanup(self.local_file.stop)
|
||||
|
||||
async def test_db_list_and_save_keep_complete_sms_payload_without_google_or_files(self):
|
||||
response = await request("POST", "/api/sms/history", SMS)
|
||||
self.assertEqual(response[0], 200)
|
||||
self.assertEqual(json.loads(response[2])["id"], 42)
|
||||
self.store.add.assert_called_once_with("sms", SMS)
|
||||
status, _, body = await request("GET", "/api/sms/history")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(json.loads(body)[0]["smsOpts"], SMS["smsOpts"])
|
||||
|
||||
async def test_sms_deletion_uses_id_and_rejects_old_index_route(self):
|
||||
self.assertEqual((await request("DELETE", "/api/sms/history/records/42"))[0], 200)
|
||||
self.store.delete.assert_called_once_with("sms", 42)
|
||||
self.assertEqual((await request("DELETE", "/api/sms/history/0"))[0], 409)
|
||||
self.store.delete.assert_called_once()
|
||||
self.assertEqual((await request("DELETE", "/api/sms/history"))[0], 200)
|
||||
self.store.clear_sms.assert_called_once()
|
||||
|
||||
async def test_db_errors_are_failures_and_do_not_report_saved_or_fall_back(self):
|
||||
self.store.add.side_effect = RuntimeError("password=do-not-print")
|
||||
response = await request("POST", "/api/sms/history", SMS)
|
||||
self.assertEqual(response[0], 503)
|
||||
self.assertNotIn("do-not-print", response[2].decode())
|
||||
self.store.list_records.side_effect = RuntimeError()
|
||||
self.assertEqual((await request("GET", "/api/sms/history"))[0], 503)
|
||||
|
||||
async def test_manual_today_display_uses_korean_date_but_save_keeps_payload(self):
|
||||
self.assertEqual((await request("POST", "/api/manual/history", MANUAL))[0], 200)
|
||||
self.assertEqual((await request("GET", "/api/manual/history"))[0], 200)
|
||||
day = self.store.list_records.call_args.kwargs["day"]
|
||||
self.assertEqual(day, datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime("%Y-%m-%d"))
|
||||
|
||||
async def test_google_saturation_does_not_block_history_reads_or_adds(self):
|
||||
with patch.object(main, "run_google_io", side_effect=AssertionError("Google saturated")):
|
||||
for method, url, payload in (("GET", "/api/sms/history", None),
|
||||
("POST", "/api/manual/history", MANUAL),
|
||||
("GET", "/api/manual/history", None)):
|
||||
self.assertEqual((await request(method, url, payload))[0], 200)
|
||||
|
||||
async def test_manual_delete_keeps_history_if_active_order_deletion_fails(self):
|
||||
with patch.object(main, "delete_manual_order_rows", side_effect=RuntimeError("google unavailable")):
|
||||
self.assertEqual((await request("DELETE", "/api/manual/history/records/42"))[0], 503)
|
||||
self.store.delete.assert_not_called()
|
||||
|
||||
async def test_manual_delete_removes_active_order_before_database_history(self):
|
||||
with patch.object(main, "delete_manual_order_rows") as remove:
|
||||
self.assertEqual((await request("DELETE", "/api/manual/history/records/42"))[0], 200)
|
||||
remove.assert_called_once_with(STAMP)
|
||||
self.store.delete.assert_called_once_with("manual", 42)
|
||||
|
||||
async def test_slow_order_cancellation_does_not_block_db_history(self):
|
||||
started, release = threading.Event(), threading.Event()
|
||||
|
||||
def stalled(timestamp):
|
||||
started.set()
|
||||
release.wait(3)
|
||||
|
||||
with patch.object(main, "delete_manual_order_rows", side_effect=stalled):
|
||||
deletion = asyncio.create_task(request("DELETE", "/api/manual/history/records/42"))
|
||||
try:
|
||||
async with asyncio.timeout(2):
|
||||
while not started.is_set():
|
||||
await asyncio.sleep(0.005)
|
||||
async with asyncio.timeout(1):
|
||||
self.assertEqual((await request("GET", "/api/sms/history"))[0], 200)
|
||||
self.assertEqual((await request("POST", "/api/sms/history", SMS))[0], 200)
|
||||
finally:
|
||||
release.set()
|
||||
self.assertEqual((await deletion)[0], 200)
|
||||
|
||||
async def test_ambiguous_manual_timestamp_does_not_delete_any_order(self):
|
||||
self.store.manual_timestamp_count.return_value = 2
|
||||
with patch.object(main, "delete_manual_order_rows") as remove:
|
||||
self.assertEqual((await request("DELETE", "/api/manual/history/records/42"))[0], 409)
|
||||
remove.assert_not_called()
|
||||
self.store.delete.assert_not_called()
|
||||
|
||||
async def test_startup_requires_history_migration_and_checks_corm_database(self):
|
||||
with patch.dict(os.environ, {"SKIP_DB_INIT": "1"}), \
|
||||
patch.object(main, "SETTINGS_BACKEND", "postgres"), \
|
||||
patch.object(main._postgres_settings, "read"):
|
||||
await main.startup_event()
|
||||
self.store.check_ready.assert_called_once()
|
||||
self.store.check_ready.side_effect = RuntimeError("missing history tables")
|
||||
with self.assertRaises(RuntimeError):
|
||||
await main.startup_event()
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.store = PostgresHistoryStore({})
|
||||
self.connection = MagicMock()
|
||||
self.cursor = self.connection.cursor.return_value.__enter__.return_value
|
||||
connect = patch.object(self.store, "_connect", return_value=self.connection)
|
||||
connect.start()
|
||||
self.addCleanup(connect.stop)
|
||||
|
||||
def test_record_id_cannot_be_spoofed_in_saved_payload(self):
|
||||
self.cursor.fetchone.return_value = (42,)
|
||||
self.store.add("sms", {**SMS, "id": 999})
|
||||
parameters = self.cursor.execute.call_args.args[1]
|
||||
self.assertNotIn("id", parameters[1].adapted)
|
||||
self.assertEqual(parameters[1].adapted["smsOpts"], SMS["smsOpts"])
|
||||
|
||||
def test_import_is_atomic_and_rejects_existing_data(self):
|
||||
self.cursor.fetchone.return_value = (True,)
|
||||
with self.assertRaises(SettingsAlreadyInitialized):
|
||||
self.store.import_all(BUNDLE, "test")
|
||||
self.assertIs(self.connection.__exit__.call_args.args[0], SettingsAlreadyInitialized)
|
||||
|
||||
def test_readback_failure_aborts_both_history_imports(self):
|
||||
self.cursor.fetchone.side_effect = [(False,), (False,), (False,)]
|
||||
self.cursor.fetchall.return_value = []
|
||||
with patch.object(history_store, "execute_values"), self.assertRaises(RuntimeError):
|
||||
self.store.import_all(BUNDLE, "test")
|
||||
self.assertIs(self.connection.__exit__.call_args.args[0], RuntimeError)
|
||||
|
||||
def test_active_order_row_deletion_never_deletes_intervening_orders(self):
|
||||
worksheet = MagicMock(id=5)
|
||||
worksheet.get_all_values.return_value = [["일시"], [STAMP], ["other"], [STAMP]]
|
||||
with patch.object(main, "get_manual_worksheet", return_value=worksheet):
|
||||
main.delete_manual_order_rows(STAMP)
|
||||
requests = worksheet.spreadsheet.batch_update.call_args.args[0]["requests"]
|
||||
self.assertEqual([r["deleteDimension"]["range"]["startIndex"] for r in requests], [3, 1])
|
||||
|
||||
|
||||
class MigrationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.backup = Path(self.directory.name) / "histories.json"
|
||||
self.store = MagicMock()
|
||||
self.store.export_all.return_value = copy.deepcopy(BUNDLE)
|
||||
for name, value in (("read_source", (copy.deepcopy(BUNDLE), "test")), ("build_store", self.store)):
|
||||
mocked = patch.object(migration, name, return_value=value)
|
||||
mocked.start()
|
||||
self.addCleanup(mocked.stop)
|
||||
self.output = io.StringIO()
|
||||
|
||||
def run_cli(self, args):
|
||||
with redirect_stdout(self.output), redirect_stderr(self.output):
|
||||
return migration.main(args)
|
||||
|
||||
def test_dry_run_does_not_connect_to_database(self):
|
||||
self.assertEqual(self.run_cli(["import"]), 0)
|
||||
migration.build_store.assert_not_called()
|
||||
|
||||
def test_source_snapshot_preserves_original_and_never_accesses_db(self):
|
||||
self.assertEqual(self.run_cli(["snapshot", "--output", str(self.backup)]), 0)
|
||||
self.assertEqual(migration.load_backup(self.backup)[0], BUNDLE)
|
||||
migration.build_store.assert_not_called()
|
||||
|
||||
def test_missing_explicit_local_file_fails_before_google_read(self):
|
||||
with patch.object(main, "get_gspread_client") as google:
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
# Call the real source reader, bypassing this class's read_source mock.
|
||||
READ_SOURCE(str(self.backup), None)
|
||||
google.assert_not_called()
|
||||
|
||||
def test_apply_saves_backup_before_any_database_write(self):
|
||||
def imported(bundle, source):
|
||||
self.assertEqual(migration.load_backup(self.backup)[0], bundle)
|
||||
self.store.import_all.side_effect = imported
|
||||
self.assertEqual(self.run_cli(["import", "--apply", "--backup", str(self.backup)]), 0)
|
||||
self.assertEqual(self.run_cli(["verify", "--input-file", str(self.backup)]), 0)
|
||||
|
||||
def test_verify_detects_data_loss_and_export_never_overwrites(self):
|
||||
self.store.export_all.return_value = {**BUNDLE, "sms": []}
|
||||
self.assertEqual(self.run_cli(["verify"]), 1)
|
||||
self.assertEqual(self.run_cli(["export", "--output", str(self.backup)]), 0)
|
||||
self.assertEqual(self.run_cli(["export", "--output", str(self.backup)]), 1)
|
||||
|
||||
def test_corrupt_local_record_or_backup_is_not_silently_skipped(self):
|
||||
self.backup.write_text("not-json\n", encoding="utf-8")
|
||||
with self.assertRaises(ValueError):
|
||||
migration.read_local_records(self.backup)
|
||||
migration.save_snapshot(self.backup.with_suffix(".other"), BUNDLE, "test")
|
||||
payload = json.loads(self.backup.with_suffix(".other").read_text(encoding="utf-8"))
|
||||
payload["rows"]["sms"] = []
|
||||
self.backup.write_text(json.dumps(payload), encoding="utf-8")
|
||||
with self.assertRaises(ValueError):
|
||||
migration.load_backup(self.backup)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,254 @@
|
||||
"""Settings compatibility, isolation from Google, migration and write conflicts."""
|
||||
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import psycopg2
|
||||
|
||||
import main
|
||||
import settings_migrate as migration
|
||||
from settings_store import (
|
||||
HEADER, PostgresSettingsStore, SettingsAlreadyInitialized, SettingsConflict,
|
||||
SettingsNotInitialized, config_to_rows, rows_to_config, settings_db_config, validate_rows,
|
||||
)
|
||||
from test_google_resilience import request
|
||||
|
||||
|
||||
ROWS = [
|
||||
HEADER.copy(),
|
||||
["APP_SETTINGS", "shipping_fee", "3500"],
|
||||
["GROUP_NAMES", "ORDER_SINGLE", "단품"],
|
||||
["ORDER_SINGLE", "상품 B", "B-2", "상품 B", "2000", "1500"],
|
||||
["ORDER_SINGLE", "---separator_1---"],
|
||||
["ORDER_SINGLE", "상품 A", "A-1", "상품 A", "1000"],
|
||||
["SMS_GIFT_RULES", "header_text", "안녕하세요\n주문 안내 😊"],
|
||||
["EMPTY", "", ""],
|
||||
]
|
||||
|
||||
|
||||
class CodecTests(unittest.TestCase):
|
||||
def test_order_separators_empty_sections_and_multiline_survive_roundtrip(self):
|
||||
restored = rows_to_config(config_to_rows(rows_to_config(ROWS)))
|
||||
self.assertEqual({s: dict(restored.items(s)) for s in restored.sections()},
|
||||
{s: dict(rows_to_config(ROWS).items(s)) for s in restored.sections()})
|
||||
self.assertEqual(list(rows_to_config(ROWS)["ORDER_SINGLE"]),
|
||||
["상품 B", "---separator_1---", "상품 A"])
|
||||
|
||||
def test_invalid_or_empty_imports_are_rejected(self):
|
||||
for rows in ([], [HEADER], [[123]], [["APP_SETTINGS", "key", "a\x00b"]], {"a": 1}):
|
||||
with self.subTest(rows=rows), self.assertRaises(ValueError):
|
||||
validate_rows(rows)
|
||||
|
||||
|
||||
class DatabaseRoutingTests(unittest.TestCase):
|
||||
def test_settings_default_is_independent_of_itemcode_db(self):
|
||||
with patch.dict(os.environ, {"ITEMCODE_DB": "existing_codes"}, clear=True):
|
||||
self.assertEqual(settings_db_config()["dbname"], "corm_db")
|
||||
self.assertEqual(migration.build_store().db_config["dbname"], "corm_db")
|
||||
|
||||
def test_explicit_settings_db_uses_existing_server_credentials(self):
|
||||
env = {"ITEMCODE_DB": "existing_codes", "SETTINGS_DB": "custom_corm",
|
||||
"POSTGRES_HOST": "shared-pg", "POSTGRES_PORT": "5433",
|
||||
"POSTGRES_USER": "app-user", "POSTGRES_PASSWORD": "test-only"}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
config = settings_db_config()
|
||||
self.assertEqual(config, {"host": "shared-pg", "port": 5433, "dbname": "custom_corm",
|
||||
"user": "app-user", "password": "test-only"})
|
||||
self.assertEqual(migration.build_store().db_config, config)
|
||||
|
||||
def test_application_settings_store_has_separate_config(self):
|
||||
self.assertIsNot(main.SETTINGS_DB_CONFIG, main.DB_CONFIG)
|
||||
self.assertEqual(main._postgres_settings.db_config, main.SETTINGS_DB_CONFIG)
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.store = PostgresSettingsStore({"host": "test-db", "password": "test-only"})
|
||||
self.connection = MagicMock()
|
||||
self.cursor = self.connection.cursor.return_value.__enter__.return_value
|
||||
self.connect = patch.object(self.store, "_connect", return_value=self.connection)
|
||||
self.connect.start()
|
||||
self.addCleanup(self.connect.stop)
|
||||
|
||||
def test_read_closes_connection_and_preserves_version(self):
|
||||
self.cursor.fetchone.return_value = (copy.deepcopy(ROWS), 7)
|
||||
self.assertEqual(self.store.read(), (ROWS, 7))
|
||||
self.connection.close.assert_called_once()
|
||||
|
||||
def test_missing_data_or_table_does_not_return_empty_settings(self):
|
||||
self.cursor.fetchone.return_value = None
|
||||
with self.assertRaises(SettingsNotInitialized):
|
||||
self.store.read()
|
||||
self.cursor.execute.side_effect = psycopg2.errors.UndefinedTable()
|
||||
with self.assertRaises(SettingsNotInitialized):
|
||||
self.store.read()
|
||||
|
||||
def test_write_uses_expected_version_and_parameterized_values(self):
|
||||
self.cursor.fetchone.return_value = (8,)
|
||||
self.assertEqual(self.store.write(ROWS, 7), 8)
|
||||
query, args = self.cursor.execute.call_args.args
|
||||
self.assertIn("AND version = %s", query)
|
||||
self.assertEqual(args[1], 7)
|
||||
self.assertEqual(args[0].adapted, ROWS)
|
||||
self.connection.__exit__.assert_called_once_with(None, None, None)
|
||||
|
||||
def test_conflict_aborts_transaction(self):
|
||||
self.cursor.fetchone.return_value = None
|
||||
with self.assertRaises(SettingsConflict):
|
||||
self.store.write(ROWS, 7)
|
||||
self.assertIs(self.connection.__exit__.call_args.args[0], SettingsConflict)
|
||||
|
||||
def test_import_never_overwrites_an_existing_document(self):
|
||||
self.cursor.fetchone.return_value = None
|
||||
with self.assertRaises(SettingsAlreadyInitialized):
|
||||
self.store.import_rows(ROWS, "test")
|
||||
self.assertIn("ON CONFLICT (id) DO NOTHING", self.cursor.execute.call_args.args[0])
|
||||
self.assertIs(self.connection.__exit__.call_args.args[0], SettingsAlreadyInitialized)
|
||||
|
||||
def test_import_readback_mismatch_aborts_before_commit(self):
|
||||
self.cursor.fetchone.side_effect = [(1,), ([HEADER],)]
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.store.import_rows(ROWS, "test")
|
||||
self.assertIs(self.connection.__exit__.call_args.args[0], RuntimeError)
|
||||
|
||||
|
||||
class PostgresApiTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
histories = patch.object(main, "HISTORY_BACKEND", "google")
|
||||
histories.start()
|
||||
self.addCleanup(histories.stop)
|
||||
self.backend = patch.object(main, "SETTINGS_BACKEND", "postgres")
|
||||
self.backend.start()
|
||||
self.addCleanup(self.backend.stop)
|
||||
self.store = MagicMock()
|
||||
self.store.read.return_value = (copy.deepcopy(ROWS), 7)
|
||||
self.store.write.return_value = 8
|
||||
self.store_patch = patch.object(main, "_postgres_settings", self.store)
|
||||
self.store_patch.start()
|
||||
self.addCleanup(self.store_patch.stop)
|
||||
self.google = patch.object(main, "get_settings_worksheet", side_effect=AssertionError("Unexpected Google I/O"))
|
||||
self.google_mock = self.google.start()
|
||||
self.addCleanup(self.google.stop)
|
||||
|
||||
async def test_config_reads_db_and_preserves_existing_api_order(self):
|
||||
status, headers, body = await request("GET", "/api/config")
|
||||
self.assertEqual(status, 200)
|
||||
data = json.loads(body)
|
||||
self.assertEqual(data["ORDER_SINGLE"]["__order"], ["상품 B", "---separator_1---", "상품 A"])
|
||||
self.assertEqual(data["SMS_GIFT_RULES"]["header_text"], "안녕하세요\n주문 안내 😊")
|
||||
self.assertEqual(headers[b"x-settings-backend"], b"postgres")
|
||||
|
||||
async def test_all_setting_endpoints_write_db_without_google(self):
|
||||
payloads = [
|
||||
("/api/app/settings", {"shipping_fee": "4000"}),
|
||||
("/api/gift/settings", {"rules": {"header_text": "새 문구"}, "app_settings": {"shipping_fee": "4500"}}),
|
||||
("/api/products/subgroup-name", {"group_key": "ORDER_SINGLE", "subgroup_index": 0, "name": "분류"}),
|
||||
("/api/products/settings", {
|
||||
"groups": [{"old_code": "ORDER_SINGLE", "new_code": "ORDER_SINGLE", "name": "단품"}],
|
||||
"products": {"ORDER_SINGLE": [{"label": "상품", "code": "NEW", "name": "새 상품", "price": 5000}]},
|
||||
}),
|
||||
]
|
||||
for url, payload in payloads:
|
||||
with self.subTest(url=url):
|
||||
self.assertEqual((await request("POST", url, payload))[0], 200)
|
||||
self.assertEqual(self.store.write.call_args.args[1], 7)
|
||||
self.google_mock.assert_not_called()
|
||||
|
||||
async def test_conflict_returns_409_and_db_failure_never_falls_back_to_google(self):
|
||||
self.store.write.side_effect = SettingsConflict("다른 요청이 변경했습니다.")
|
||||
self.assertEqual((await request("POST", "/api/app/settings", {"shipping_fee": "4000"}))[0], 409)
|
||||
self.store.read.side_effect = RuntimeError("database unavailable")
|
||||
self.assertEqual((await request("GET", "/api/config"))[0], 503)
|
||||
self.google_mock.assert_not_called()
|
||||
|
||||
async def test_google_saturation_does_not_block_db_settings_reads_or_saves(self):
|
||||
with patch.object(main, "run_google_io", side_effect=AssertionError("Google pool unavailable")):
|
||||
self.assertEqual((await request("GET", "/api/config"))[0], 200)
|
||||
self.assertEqual((await request("POST", "/api/app/settings", {"font": "Arial"}))[0], 200)
|
||||
|
||||
async def test_postgres_startup_does_not_refresh_google(self):
|
||||
with patch.dict(os.environ, {"SKIP_DB_INIT": "1"}), \
|
||||
patch.object(main._settings_cache, "refresh_in_background") as refresh:
|
||||
await main.startup_event()
|
||||
refresh.assert_not_called()
|
||||
self.store.read.assert_called_once()
|
||||
|
||||
async def test_startup_rejects_incomplete_migration(self):
|
||||
self.store.read.side_effect = SettingsNotInitialized("missing")
|
||||
with patch.dict(os.environ, {"SKIP_DB_INIT": "1"}), self.assertRaises(SettingsNotInitialized):
|
||||
await main.startup_event()
|
||||
|
||||
|
||||
class MigrationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.backup = Path(self.directory.name) / "settings.json"
|
||||
self.store = MagicMock()
|
||||
self.store.read.return_value = (copy.deepcopy(ROWS), 1)
|
||||
self.store.import_rows.return_value = 1
|
||||
for name, value in (("read_google_rows", (copy.deepcopy(ROWS), "google:test:설정")),
|
||||
("build_store", self.store)):
|
||||
patched = patch.object(migration, name, return_value=value)
|
||||
patched.start()
|
||||
self.addCleanup(patched.stop)
|
||||
self.output = io.StringIO()
|
||||
|
||||
def run_cli(self, args):
|
||||
with redirect_stdout(self.output), redirect_stderr(self.output):
|
||||
return migration.main(args)
|
||||
|
||||
def test_dry_run_never_connects_to_or_writes_db(self):
|
||||
self.assertEqual(self.run_cli(["import"]), 0)
|
||||
migration.build_store.assert_not_called()
|
||||
|
||||
def test_apply_backs_up_before_import_and_does_not_overwrite_backups(self):
|
||||
def check_backup(rows, source):
|
||||
self.assertEqual(migration.load_snapshot(self.backup)[0], rows)
|
||||
return 1
|
||||
self.store.import_rows.side_effect = check_backup
|
||||
args = ["import", "--apply", "--backup", str(self.backup)]
|
||||
self.assertEqual(self.run_cli(args), 0)
|
||||
self.assertEqual(self.run_cli(args), 1)
|
||||
self.store.import_rows.assert_called_once()
|
||||
|
||||
def test_apply_requires_backup_before_source_or_db_access(self):
|
||||
with self.assertRaises(SystemExit), redirect_stderr(self.output):
|
||||
migration.main(["import", "--apply"])
|
||||
migration.read_google_rows.assert_not_called()
|
||||
migration.build_store.assert_not_called()
|
||||
|
||||
def test_backup_checksum_rejects_modified_content(self):
|
||||
migration.save_snapshot(self.backup, ROWS, "test")
|
||||
payload = json.loads(self.backup.read_text(encoding="utf-8"))
|
||||
payload["rows"][1][2] = "9999"
|
||||
self.backup.write_text(json.dumps(payload), encoding="utf-8")
|
||||
with self.assertRaises(ValueError):
|
||||
migration.load_snapshot(self.backup)
|
||||
|
||||
def test_verify_detects_order_or_cell_differences(self):
|
||||
self.assertEqual(self.run_cli(["verify"]), 0)
|
||||
self.store.read.return_value = (list(reversed(ROWS)), 1)
|
||||
self.assertEqual(self.run_cli(["verify"]), 1)
|
||||
self.store.import_rows.assert_not_called()
|
||||
|
||||
def test_export_and_offline_import_need_no_google(self):
|
||||
self.assertEqual(self.run_cli(["export", "--output", str(self.backup)]), 0)
|
||||
self.assertEqual(self.run_cli(["import", "--input-file", str(self.backup)]), 0)
|
||||
migration.read_google_rows.assert_not_called()
|
||||
|
||||
def test_errors_do_not_print_database_credentials(self):
|
||||
self.store.import_rows.side_effect = RuntimeError("password=secret-value")
|
||||
self.assertEqual(self.run_cli(["import", "--apply", "--backup", str(self.backup)]), 1)
|
||||
self.assertNotIn("secret-value", self.output.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Opt-in real PostgreSQL tests, confined to a newly created temporary schema.
|
||||
|
||||
SETTINGS_TEST_DSN must point to a disposable test database, never production.
|
||||
"""
|
||||
|
||||
import os
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import psycopg2
|
||||
from psycopg2 import sql
|
||||
|
||||
from settings_store import (
|
||||
HEADER, PostgresSettingsStore, SettingsAlreadyInitialized, SettingsConflict,
|
||||
SettingsNotInitialized,
|
||||
)
|
||||
from history_store import PostgresHistoryStore
|
||||
|
||||
|
||||
@unittest.skipUnless(os.getenv("SETTINGS_TEST_DSN"), "SETTINGS_TEST_DSN test database is not configured")
|
||||
class RealPostgresTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dsn = os.environ["SETTINGS_TEST_DSN"]
|
||||
self.schema = "corm_settings_test_" + uuid.uuid4().hex
|
||||
connection = psycopg2.connect(self.dsn, connect_timeout=3)
|
||||
try:
|
||||
with connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(self.schema)))
|
||||
finally:
|
||||
connection.close()
|
||||
self.addCleanup(self.drop_schema)
|
||||
self.store = PostgresSettingsStore({})
|
||||
self.store._connect = self.connect
|
||||
self.histories = PostgresHistoryStore({})
|
||||
self.histories._connect = self.connect
|
||||
self.rows = [HEADER.copy(), ["APP_SETTINGS", "font", "한글 😊"],
|
||||
["ORDER_SINGLE", "B", "B-1"], ["ORDER_SINGLE", "A", "A-1"]]
|
||||
|
||||
def connect(self):
|
||||
connection = psycopg2.connect(self.dsn, connect_timeout=3)
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(sql.SQL("SET search_path TO {}").format(sql.Identifier(self.schema)))
|
||||
cursor.execute("SET statement_timeout = 5000")
|
||||
return connection
|
||||
|
||||
def drop_schema(self):
|
||||
assert self.schema.startswith("corm_settings_test_") and len(self.schema) == 51
|
||||
connection = psycopg2.connect(self.dsn, connect_timeout=3)
|
||||
try:
|
||||
with connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql.SQL("DROP SCHEMA {} CASCADE").format(sql.Identifier(self.schema)))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def test_jsonb_roundtrip_update_and_duplicate_import(self):
|
||||
self.assertEqual(self.store.import_rows(self.rows, "test"), 1)
|
||||
self.assertEqual(self.store.read(), (self.rows, 1))
|
||||
with self.assertRaises(SettingsAlreadyInitialized):
|
||||
self.store.import_rows(list(reversed(self.rows)), "test")
|
||||
self.assertEqual(self.store.read(), (self.rows, 1))
|
||||
changed = self.rows + [["APP_SETTINGS", "shipping_fee", "4000"]]
|
||||
self.assertEqual(self.store.write(changed, 1), 2)
|
||||
self.assertEqual(self.store.read(), (changed, 2))
|
||||
|
||||
def test_two_connections_cannot_silently_overwrite_each_other(self):
|
||||
self.store.import_rows(self.rows, "test")
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def save(value):
|
||||
rows, version = self.store.read()
|
||||
rows.append(["APP_SETTINGS", "shipping_fee", value])
|
||||
barrier.wait(timeout=3)
|
||||
try:
|
||||
self.store.write(rows, version)
|
||||
return "saved"
|
||||
except SettingsConflict:
|
||||
return "conflict"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
self.assertCountEqual(list(executor.map(save, ["4000", "5000"])), ["saved", "conflict"])
|
||||
self.assertEqual(self.store.read()[1], 2)
|
||||
|
||||
def test_failed_import_rolls_back_table_and_data(self):
|
||||
with self.assertRaises(psycopg2.IntegrityError):
|
||||
self.store.import_rows(self.rows, None)
|
||||
with self.assertRaises(SettingsNotInitialized):
|
||||
self.store.read()
|
||||
|
||||
def test_history_import_full_payload_ids_filters_and_deletion(self):
|
||||
sms = {"timestamp": "2026-10-22 12:00:00", "items": [{"code": "TEST", "qty": 2}],
|
||||
"previewText": "문자\n두 줄", "smsOpts": {"discount": True}}
|
||||
manual = [{"timestamp": "2020-01-01 10:00:00", "total_amount": "누락"},
|
||||
{"timestamp": "2026-10-22 12:00:00", "total_amount": 3500}]
|
||||
bundle = {"kind": "corm-history", "sms": [sms], "manual": manual}
|
||||
self.histories.import_all(bundle, "test")
|
||||
self.histories.check_ready()
|
||||
with self.assertRaises(SettingsAlreadyInitialized):
|
||||
self.histories.import_all(bundle, "test")
|
||||
saved = self.histories.list_records("sms")
|
||||
self.assertEqual(saved[0]["smsOpts"], sms["smsOpts"])
|
||||
self.assertEqual(len(self.histories.list_records("manual", "2026-10-22")), 1)
|
||||
self.assertEqual(len(self.histories.export_all()["manual"]), 2)
|
||||
new_id = self.histories.add("sms", {**sms, "timestamp": "2026-10-22 12:00:01"})
|
||||
self.histories.delete("sms", saved[0]["id"])
|
||||
self.assertEqual([r["id"] for r in self.histories.list_records("sms")], [new_id])
|
||||
self.histories.clear_sms()
|
||||
self.assertEqual(self.histories.list_records("sms"), [])
|
||||
with self.assertRaises(SettingsAlreadyInitialized):
|
||||
self.histories.import_all(bundle, "test")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user