"""Editable manual-order queue, with atomic cell updates and recoverable exports.""" import io import re import uuid from contextlib import closing from openpyxl import Workbook from openpyxl.styles import Alignment, Font, PatternFill from psycopg2.extras import Json, execute_values from history_store import normalize_record from settings_store import PostgresSettingsStore, SettingsAlreadyInitialized, SettingsNotInitialized HEADERS = ["주문날짜", "번호", "주문번호", "수령인명", "상품코드", "상품명", "주문수량", "주소", "우편번호", "수령인 전화번호", "수령인 휴대폰", "배송시 요구사항", "송장번호", "주문처", "비고"] class CellConflict(RuntimeError): def __init__(self, rows): self.rows = rows super().__init__("다른 사용자가 수정한 셀이 있습니다. 최신값을 확인해주세요.") def validate_source(source): if not isinstance(source, dict) or source.get("kind") != "corm-manual-orders": raise ValueError("수동발주 원본이 필요합니다.") headers, rows = source.get("headers"), source.get("rows") if not isinstance(headers, list) or len(headers) < 15 or len(headers) > 100 or not all(isinstance(x, str) for x in headers): raise ValueError("원본 열 구성을 확인해주세요.") if not isinstance(rows, list) or not all(isinstance(row, list) and len(row) <= len(headers) and all(isinstance(x, str) and "\x00" not in x for x in row) for row in rows): raise ValueError("원본 셀 형식을 확인해주세요.") return headers, [row + [""] * (len(headers) - len(row)) for row in rows] def build_xlsx(headers, rows): workbook = Workbook() sheet = workbook.active sheet.title = "수동 발주" for index, values in enumerate([headers] + rows, start=1): for column, value in enumerate(values, start=1): numeric = index > 1 and column in (3, 7) and re.fullmatch(r"-?(?:0|[1-9][0-9]{0,14})", value.replace(",", "")) cell = sheet.cell(index, column, int(value.replace(",", "")) if numeric else value) # IDs, phone numbers, leading zeros and '=' always remain literal text. if not numeric: cell.data_type = "s" cell.alignment = Alignment(vertical="top", wrap_text=True) if index == 1: cell.font = Font(bold=True, color="FFFFFF") cell.fill = PatternFill("solid", fgColor="334155") sheet.freeze_panes = "A2" sheet.auto_filter.ref = sheet.dimensions for column in sheet.columns: sheet.column_dimensions[column[0].column_letter].width = 21 sheet.column_dimensions["H"].width = 45 sheet.column_dimensions["O"].width = 45 output = io.BytesIO() workbook.save(output) return output.getvalue() class ManualOrderStore: def __init__(self, config): self.database = PostgresSettingsStore(config) def _connect(self): return self.database._connect() @staticmethod def _schema(cursor): cursor.execute("""CREATE TABLE IF NOT EXISTS corm_manual_sheet ( id SMALLINT PRIMARY KEY CHECK(id=1), headers JSONB NOT NULL, source TEXT NOT NULL, imported_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP)""") cursor.execute("""CREATE TABLE IF NOT EXISTS corm_manual_orders ( id BIGSERIAL PRIMARY KEY, order_key TEXT NOT NULL, cells JSONB NOT NULL, version BIGINT NOT NULL DEFAULT 1, archived_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP)""") cursor.execute("CREATE INDEX IF NOT EXISTS corm_manual_orders_active ON corm_manual_orders(id) WHERE archived_at IS NULL") cursor.execute("CREATE INDEX IF NOT EXISTS corm_manual_orders_key ON corm_manual_orders(order_key)") cursor.execute("""CREATE TABLE IF NOT EXISTS corm_manual_exports ( id UUID PRIMARY KEY, filename TEXT NOT NULL, content BYTEA NOT NULL, row_ids JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP)""") def check_ready(self): self.list_rows() def list_rows(self): with closing(self._connect()) as connection, connection, connection.cursor() as cursor: cursor.execute("SELECT headers FROM corm_manual_sheet WHERE id=1") metadata = cursor.fetchone() if metadata is None: raise SettingsNotInitialized("수동발주 이전을 먼저 실행해주세요.") cursor.execute("SELECT id, cells, version FROM corm_manual_orders WHERE archived_at IS NULL ORDER BY id") return {"headers": metadata[0], "rows": [dict(zip(("id", "cells", "version"), row)) for row in cursor.fetchall()]} def import_source(self, source, label): headers, rows = validate_source(source) with closing(self._connect()) as connection, connection, connection.cursor() as cursor: self._schema(cursor) cursor.execute("LOCK TABLE corm_manual_sheet, corm_manual_orders IN EXCLUSIVE MODE") cursor.execute("SELECT EXISTS(SELECT 1 FROM corm_manual_sheet) OR EXISTS(SELECT 1 FROM corm_manual_orders)") if cursor.fetchone()[0]: raise SettingsAlreadyInitialized("기존 발주 DB를 덮어쓰지 않았습니다.") cursor.execute("INSERT INTO corm_manual_sheet(id,headers,source) VALUES(1,%s,%s)", (Json(headers), label)) if rows: execute_values(cursor, "INSERT INTO corm_manual_orders(order_key,cells) VALUES %s", [("legacy:" + row[0] if row[0] else "legacy-row:" + str(i), Json(row)) for i, row in enumerate(rows)]) cursor.execute("SELECT cells FROM corm_manual_orders ORDER BY id") if [row[0] for row in cursor.fetchall()] != rows: raise RuntimeError("발주 원본 검증 실패.") def append(self, rows, history=None): with closing(self._connect()) as connection, connection, connection.cursor() as cursor: cursor.execute("SELECT headers FROM corm_manual_sheet WHERE id=1") metadata = cursor.fetchone() if not metadata: raise SettingsNotInitialized("수동발주 이전이 필요합니다.") key = str(uuid.uuid4()) _, normalized = validate_source({"kind": "corm-manual-orders", "headers": metadata[0], "rows": [[str(x) for x in row] for row in rows]}) for row in normalized: cursor.execute("INSERT INTO corm_manual_orders(order_key,cells) VALUES(%s,%s)", (key, Json(row))) if history is not None: record = normalize_record("manual", {**history, "manual_order_key": key}) cursor.execute("INSERT INTO corm_manual_history(occurred_at,payload) VALUES(%s,%s)", (record["timestamp"], Json(record))) return key def patch_cells(self, changes): if not changes or len(changes) > 2000 or len({(c["id"], c["column"]) for c in changes}) != len(changes): raise ValueError("한 번에 수정할 셀을 확인해주세요.") with closing(self._connect()) as connection, connection, connection.cursor() as cursor: cursor.execute("SELECT id,cells,version FROM corm_manual_orders WHERE id=ANY(%s) AND archived_at IS NULL ORDER BY id FOR UPDATE", (sorted({c["id"] for c in changes}),)) rows = {row[0]: {"id": row[0], "cells": row[1], "version": row[2]} for row in cursor.fetchall()} if len(rows) != len({c["id"] for c in changes}): raise LookupError("이미 내려받았거나 삭제된 행입니다. 표를 새로고침해주세요.") conflicts = [] for change in changes: row = rows[change["id"]] column = change["column"] if column < 0 or column >= len(row["cells"]) or len(change["value"]) > 20000 or "\x00" in change["value"]: raise ValueError("셀 내용을 확인해주세요.") actual = row["cells"][column] if actual != change["previous_value"] and actual != change["value"]: conflicts.append({"id": row["id"], "column": column, "value": actual}) if conflicts: raise CellConflict(conflicts) for change in changes: rows[change["id"]]["cells"][change["column"]] = change["value"] for row in rows.values(): cursor.execute("UPDATE corm_manual_orders SET cells=%s,version=version+1 WHERE id=%s RETURNING version", (Json(row["cells"]), row["id"])) row["version"] = cursor.fetchone()[0] return list(rows.values()) def archive_rows(self, rows): with closing(self._connect()) as connection, connection, connection.cursor() as cursor: cursor.execute("SELECT id,version FROM corm_manual_orders WHERE id=ANY(%s) AND archived_at IS NULL ORDER BY id FOR UPDATE", ([r["id"] for r in rows],)) versions = dict(cursor.fetchall()) if any(versions.get(r["id"]) != r["version"] for r in rows): raise CellConflict([]) cursor.execute("UPDATE corm_manual_orders SET archived_at=CURRENT_TIMESTAMP WHERE id=ANY(%s)", ([r["id"] for r in rows],)) def export_and_archive(self, filename): with closing(self._connect()) as connection, connection, connection.cursor() as cursor: cursor.execute("SELECT headers FROM corm_manual_sheet WHERE id=1") headers = cursor.fetchone()[0] cursor.execute("SELECT id,cells FROM corm_manual_orders WHERE archived_at IS NULL ORDER BY id FOR UPDATE") rows = cursor.fetchall() content = build_xlsx(headers, [row[1] for row in rows]) export_id = str(uuid.uuid4()) cursor.execute("INSERT INTO corm_manual_exports(id,filename,content,row_ids) VALUES(%s,%s,%s,%s)", (export_id, filename, content, Json([row[0] for row in rows]))) cursor.execute("UPDATE corm_manual_orders SET archived_at=CURRENT_TIMESTAMP WHERE id=ANY(%s)", ([row[0] for row in rows],)) return content, export_id def exports(self, export_id=None): with closing(self._connect()) as connection, connection, connection.cursor() as cursor: if export_id: cursor.execute("SELECT filename,content FROM corm_manual_exports WHERE id=%s", (export_id,)) row = cursor.fetchone() if row is None: raise LookupError("다운로드 기록이 없습니다.") return row[0], bytes(row[1]) cursor.execute("SELECT id,filename,created_at FROM corm_manual_exports ORDER BY created_at DESC LIMIT 10") return [{"id": str(r[0]), "filename": r[1], "created_at": r[2].isoformat()} for r in cursor.fetchall()] def delete_history(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 FOR UPDATE", (record_id,)) record = cursor.fetchone() if record is None: raise LookupError("이미 삭제된 내역입니다.") payload = record[0] key = payload.get("manual_order_key") if not key: cursor.execute("SELECT count(*) FROM corm_manual_history WHERE occurred_at=%s", (payload["timestamp"],)) if cursor.fetchone()[0] > 1: raise ValueError("같은 일시의 내역이 여러 건입니다. 수동발주 표에서 대상 주문을 먼저 확인해주세요.") key = "legacy:" + payload["timestamp"] cursor.execute("UPDATE corm_manual_orders SET archived_at=CURRENT_TIMESTAMP WHERE order_key=%s AND archived_at IS NULL", (key,)) cursor.execute("DELETE FROM corm_manual_history WHERE id=%s", (record_id,))