Files
Aislo/B02_ProjRegister/B02_ProjRegister_Repository.py
T
eomsangdonandClaude Opus 5 aed7465a5f feat(B01,B02): 프로젝트 참여자 다중 지정·가입요청 목록 정리·서명 문구 개선
- project_members 표 신설(016 마이그레이션, 기존 프로젝트는 생성자 자동 채움)
- 프로젝트 수정 모달에 참여자 선택 추가, 참여자로 지정된 일반사용자는 해당 프로젝트 수정 가능 (백엔드 _can_edit_project 동반 수정)
- B02 프로젝트 생성 시 생성자를 참여자로 자동 등록, 참여자도 같은 회사 구성원인지 검증
- 가입 요청 목록을 대기 상태만 표시 (처리 완료 건이 사용자 관리 목록과 중복 노출되던 문제)
- 팀원 등록 시 남아 있던 가입 신청 자동 정리
- 서명·로고 선택 문구를 뜻이 드러나게 수정

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 11:33:18 +09:00

159 lines
6.1 KiB
Python

"""B02_ProjRegister aiomysql Raw SQL 저장소."""
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
import aiomysql
from common_util.common_util_json import atomic_write_json
from common_util.common_util_storage import PROJECT_STORAGE_LAYOUT_V2
from common_util.common_util_workflow import load_project_workflow
from common_util.common_util_workflow_state import initialize_project_stages
from config.config_db import get_db_pool
from config.config_system import STORAGE_BASE_DIR
def _build_project_storage(company_id: int, user_id: int, project_id: str) -> tuple[str, Path]:
relative_path = f"storage/{company_id}/{user_id}/{project_id}"
storage_root = Path(STORAGE_BASE_DIR).resolve()
project_root = (storage_root / str(company_id) / str(user_id) / project_id).resolve()
if storage_root not in (project_root, *project_root.parents):
raise ValueError("프로젝트 저장 경로가 저장소 루트를 벗어났습니다.")
return relative_path, project_root
def _initialize_project_storage(project_root: Path, project_id: str) -> None:
for stage, subdir in PROJECT_STORAGE_LAYOUT_V2:
(project_root / stage / subdir).mkdir(parents=True, exist_ok=True)
atomic_write_json(project_root / "workflow.json", load_project_workflow(project_root))
atomic_write_json(
project_root / "project_manifest.json",
{
"project_id": project_id,
"storage_version": 2,
"created_at": datetime.utcnow().isoformat(timespec="seconds"),
"stages": [f"{stage}/{subdir}" for stage, subdir in PROJECT_STORAGE_LAYOUT_V2],
},
)
async def create_project(
*,
user_id: int,
company_id: int,
name: str,
region: str,
road_type: str,
project_year: int,
estimated_length_m: float | None,
memo: str | None,
title_block: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""신규 프로젝트를 DB에 저장하고 워크플로우 저장소를 초기화한다."""
project_id = str(uuid4())
fields = title_block or {}
storage_path, project_root = _build_project_storage(company_id, user_id, project_id)
now = datetime.utcnow()
pool = get_db_pool()
async with pool.acquire() as connection, connection.cursor(aiomysql.DictCursor) as cursor:
try:
await connection.begin()
await cursor.execute(
"""
INSERT INTO projects (
id, user_id, company_id, name, region, road_type,
project_year, estimated_length_m, route_start_m, route_end_m,
memo, status,
crs_epsg, storage_path, created_at, updated_at,
client_org, project_number, work_amount, design_date,
pm_user_id, field_lead_user_id, designer_user_id, logo_asset_id
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'NEW', 5178, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s)
""",
(
project_id,
user_id,
company_id,
name,
region,
road_type,
project_year,
estimated_length_m,
fields.get("route_start_m"),
fields.get("route_end_m"),
memo,
storage_path,
now,
now,
fields.get("client_org"),
fields.get("project_number"),
fields.get("work_amount"),
fields.get("design_date"),
fields.get("pm_user_id"),
fields.get("field_lead_user_id"),
fields.get("designer_user_id"),
fields.get("logo_asset_id"),
),
)
# 만든 사람은 곧 참여자다 (2026-09-06 사용자 확정) — 참여자는 수정 권한을 가진다.
await cursor.execute(
"INSERT IGNORE INTO project_members (project_id, user_id) VALUES (%s, %s)",
(project_id, user_id),
)
# 워크플로우 단계별 상태 초기화 시드
await initialize_project_stages(cursor, project_id)
await cursor.execute(
"""INSERT INTO system_audit_logs (user_id, action, resource_type, resource_id)
VALUES (%s, 'PROJECT_CREATE', 'project', NULL)""",
(user_id,),
)
_initialize_project_storage(project_root, project_id)
await connection.commit()
except Exception:
await connection.rollback()
raise
await cursor.execute(
"""
SELECT id AS project_id, name, region, road_type, project_year,
estimated_length_m, route_start_m, route_end_m,
memo, status, storage_path,
DATE_FORMAT(created_at, '%%Y-%%m-%%dT%%H:%%i:%%s') AS created_at
FROM projects
WHERE id = %s
""",
(project_id,),
)
row = await cursor.fetchone()
if not row:
raise RuntimeError("생성된 프로젝트를 다시 조회할 수 없습니다.")
return dict(row)
async def get_project_by_id(project_id: str) -> dict[str, Any] | None:
"""프로젝트 단건 조회."""
pool = get_db_pool()
async with pool.acquire() as connection, connection.cursor(aiomysql.DictCursor) as cursor:
await cursor.execute(
"""
SELECT id AS project_id, user_id, company_id, name, region, road_type,
project_year, estimated_length_m, route_start_m, route_end_m,
memo, status, storage_path,
DATE_FORMAT(created_at, '%%Y-%%m-%%dT%%H:%%i:%%s') AS created_at
FROM projects
WHERE id = %s AND deleted_at IS NULL
""",
(project_id,),
)
return await cursor.fetchone()