Add database-backed manual order grid with automatic cell saving
This commit is contained in:
@@ -41,6 +41,7 @@ from settings_store import (
|
||||
config_to_rows, rows_to_config, settings_db_config,
|
||||
)
|
||||
from history_store import PostgresHistoryStore
|
||||
from manual_orders import ManualOrderStore, CellConflict
|
||||
|
||||
# ==========================================
|
||||
# SSO / 서브경로 호스팅 설정
|
||||
@@ -73,6 +74,12 @@ 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)
|
||||
MANUAL_ORDERS_BACKEND = os.getenv("MANUAL_ORDERS_BACKEND", "google").strip().lower()
|
||||
if MANUAL_ORDERS_BACKEND not in {"google", "postgres"}:
|
||||
raise RuntimeError("MANUAL_ORDERS_BACKEND는 google 또는 postgres여야 합니다.")
|
||||
if MANUAL_ORDERS_BACKEND == "postgres" and HISTORY_BACKEND != "postgres":
|
||||
raise RuntimeError("DB 수동발주는 HISTORY_BACKEND=postgres가 필요합니다.")
|
||||
_manual_orders = ManualOrderStore(SETTINGS_DB_CONFIG)
|
||||
|
||||
# 2. 반품 데이터 저장용 DB
|
||||
RETURN_DB_CONFIG = {
|
||||
@@ -249,6 +256,28 @@ def history_db_call(method, *args, **kwargs):
|
||||
raise HTTPException(status_code=503, detail="DB 내역 처리를 확인하지 못했습니다. 새로고침하여 확인해주세요.") from exc
|
||||
|
||||
|
||||
def manual_worker(function):
|
||||
@functools.wraps(function)
|
||||
async def wrapped(*args, **kwargs):
|
||||
if MANUAL_ORDERS_BACKEND == "postgres":
|
||||
return await run_in_threadpool(function, *args, **kwargs)
|
||||
return await run_google_io(function, *args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
def manual_db_call(method, *args, **kwargs):
|
||||
try:
|
||||
return getattr(_manual_orders, method)(*args, **kwargs)
|
||||
except CellConflict as exc:
|
||||
raise HTTPException(status_code=409, detail={"message": str(exc), "conflicts": exc.rows}) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="수동발주 저장을 확인하지 못했습니다. 입력을 보존한 후 다시 시도해주세요.") from exc
|
||||
|
||||
|
||||
def read_config(force_refresh=False):
|
||||
if SETTINGS_BACKEND == "postgres":
|
||||
try:
|
||||
@@ -336,6 +365,7 @@ async def index(request: Request):
|
||||
"root_path": APP_ROOT_PATH,
|
||||
"user_email": getattr(request.state, "erp_user", {}).get("email", ""),
|
||||
"user_name": getattr(request.state, "erp_user", {}).get("name", ""),
|
||||
"manual_orders_backend": MANUAL_ORDERS_BACKEND,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -583,9 +613,11 @@ async def startup_event():
|
||||
_settings_cache.refresh_in_background(_load_settings_rows)
|
||||
if HISTORY_BACKEND == "postgres":
|
||||
await run_in_threadpool(_postgres_history.check_ready)
|
||||
if MANUAL_ORDERS_BACKEND == "postgres":
|
||||
await run_in_threadpool(_manual_orders.check_ready)
|
||||
|
||||
@app.post("/api/order/submit")
|
||||
@google_worker
|
||||
@manual_worker
|
||||
def submit_order_submit(payload: OrderPayload):
|
||||
date_str, time_str, current_datetime_str = get_current_time_info()
|
||||
c_tel = format_phone_number(payload.phone)
|
||||
@@ -601,8 +633,6 @@ def submit_order_submit(payload: OrderPayload):
|
||||
title = "재구매"
|
||||
|
||||
try:
|
||||
worksheet = get_manual_worksheet()
|
||||
|
||||
rows = []
|
||||
lines = []
|
||||
for i, item in enumerate(payload.items):
|
||||
@@ -618,7 +648,12 @@ def submit_order_submit(payload: OrderPayload):
|
||||
rows.append(row_data)
|
||||
|
||||
if rows:
|
||||
worksheet.append_rows(rows, value_input_option='USER_ENTERED')
|
||||
if MANUAL_ORDERS_BACKEND == "postgres":
|
||||
manual_db_call("append", rows, {"timestamp": current_datetime_str,
|
||||
"customer_name": payload.customer_name,
|
||||
"total_amount": order_status or payload.total_amount})
|
||||
else:
|
||||
get_manual_worksheet().append_rows(rows, value_input_option='USER_ENTERED')
|
||||
|
||||
clipboard_text = "\r\n".join(lines) + "\r\n"
|
||||
cs_record_saved_count = 0
|
||||
@@ -635,21 +670,104 @@ def submit_order_submit(payload: OrderPayload):
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"{len(rows)}개 항목 구글 시트 입력 및 클립보드 준비 완료.",
|
||||
"message": f"{len(rows)}개 항목 발주 입력 및 클립보드 준비 완료.",
|
||||
"history_saved": MANUAL_ORDERS_BACKEND == "postgres",
|
||||
"clipboard_text": clipboard_text,
|
||||
"timestamp": current_datetime_str,
|
||||
"cs_record_saved_count": cs_record_saved_count,
|
||||
"cs_record_warning": cs_record_warning,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
err_str = str(e)
|
||||
if not err_str or err_str.strip() == "{}":
|
||||
err_str = repr(e)
|
||||
raise HTTPException(status_code=500, detail=f"수동발주 시트 접근 에러 (스프레드시트에 이메일 편집 권한을 추가했는지 확인해주세요!): {err_str}")
|
||||
|
||||
def manual_file_response(content, filename, export_id=None):
|
||||
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"}
|
||||
if export_id:
|
||||
headers["X-Manual-Export-ID"] = export_id
|
||||
return StreamingResponse(io.BytesIO(content),
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers=headers)
|
||||
|
||||
|
||||
class ManualCellChange(BaseModel):
|
||||
id: int
|
||||
column: int
|
||||
value: str
|
||||
previous_value: str
|
||||
|
||||
|
||||
class ManualCellChanges(BaseModel):
|
||||
changes: List[ManualCellChange]
|
||||
|
||||
|
||||
class ManualRowVersion(BaseModel):
|
||||
id: int
|
||||
version: int
|
||||
|
||||
|
||||
class ManualRowsToArchive(BaseModel):
|
||||
rows: List[ManualRowVersion]
|
||||
|
||||
|
||||
def require_manual_db():
|
||||
if MANUAL_ORDERS_BACKEND != "postgres":
|
||||
raise HTTPException(status_code=409, detail="수동발주 DB 이전 후 사용할 수 있습니다.")
|
||||
|
||||
|
||||
@app.get("/api/manual/orders")
|
||||
def get_manual_orders():
|
||||
require_manual_db()
|
||||
return manual_db_call("list_rows")
|
||||
|
||||
|
||||
@app.post("/api/manual/orders")
|
||||
def add_manual_order_row():
|
||||
require_manual_db()
|
||||
manual_db_call("append", [[get_current_time_info()[2]] + [""] * 14])
|
||||
return {"status": "success"}
|
||||
|
||||
|
||||
@app.patch("/api/manual/orders/cells")
|
||||
def patch_manual_order_cells(payload: ManualCellChanges):
|
||||
require_manual_db()
|
||||
return {"rows": manual_db_call("patch_cells", [dict(change) for change in payload.changes])}
|
||||
|
||||
|
||||
@app.post("/api/manual/orders/archive")
|
||||
def archive_manual_order_rows(payload: ManualRowsToArchive):
|
||||
require_manual_db()
|
||||
if not payload.rows or len(payload.rows) > 2000:
|
||||
raise HTTPException(status_code=400, detail="삭제할 행을 선택해주세요.")
|
||||
manual_db_call("archive_rows", [dict(row) for row in payload.rows])
|
||||
return {"status": "success"}
|
||||
|
||||
|
||||
@app.get("/api/manual/orders/exports")
|
||||
def get_manual_exports():
|
||||
require_manual_db()
|
||||
return manual_db_call("exports")
|
||||
|
||||
|
||||
@app.get("/api/manual/orders/exports/{export_id}")
|
||||
def get_manual_export(export_id: uuid.UUID):
|
||||
require_manual_db()
|
||||
filename, content = manual_db_call("exports", str(export_id))
|
||||
return manual_file_response(content, filename)
|
||||
|
||||
|
||||
@app.post("/api/sheet/download_and_clear")
|
||||
@google_worker
|
||||
@manual_worker
|
||||
def download_and_clear_sheet():
|
||||
if MANUAL_ORDERS_BACKEND == "postgres":
|
||||
now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
|
||||
weekdays = ["월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"]
|
||||
filename = f"{now:%m}월 {now:%d}일 ({weekdays[now.weekday()]}) 5 수동발주.xlsx"
|
||||
content, export_id = manual_db_call("export_and_archive", filename)
|
||||
return manual_file_response(content, filename, export_id)
|
||||
try:
|
||||
scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
|
||||
creds = load_service_account_credentials(scopes)
|
||||
@@ -994,11 +1112,14 @@ def delete_manual_order_rows(timestamp):
|
||||
|
||||
|
||||
@app.delete("/api/manual/history/records/{record_id}")
|
||||
@google_worker
|
||||
@manual_worker
|
||||
@google_history_access
|
||||
def delete_manual_history_record(record_id: int):
|
||||
if HISTORY_BACKEND != "postgres":
|
||||
raise HTTPException(status_code=409, detail="내역 화면을 새로고침해주세요.")
|
||||
if MANUAL_ORDERS_BACKEND == "postgres":
|
||||
manual_db_call("delete_history", record_id)
|
||||
return {"status": "success"}
|
||||
record = history_db_call("get_manual", record_id)
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail="이미 삭제된 내역입니다. 새로고침해주세요.")
|
||||
|
||||
Reference in New Issue
Block a user