"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 PostgreSQL + FastAPI TestClient). 운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 가상의 사용자·프로젝트만 만든다. # 1) 로컬 테스트 DB 에 스키마 적용(최초 1회): project_db_init.sql + project_db_0*.sql # 2) 실행 PROJECT_TEST_DB_URL=postgresql://postgres@localhost:55432/project_db \ python tests/test_project_module.py PROJECT_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호). 메일은 app.mail.send_email 을 가짜로 바꿔 기록만 한다(실제 발송 없음). """ from __future__ import annotations import io import os import sys import tempfile import threading import types import uuid from datetime import date, timedelta from urllib.parse import urlparse sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DSN = os.getenv("PROJECT_TEST_DB_URL", "") _host = urlparse(DSN).hostname if DSN else None ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1") # ── app.main 대역(전체 앱을 띄우지 않고 프로젝트 라우터만 시험) ────────────── class _Users: def __init__(self) -> None: self.d: dict[str, dict] = {} def add(self, email: str, *, role: str = "user", project: bool = True, super_: bool = False) -> str: email = email.lower() self.d[email] = {"email": email, "name": email.split("@")[0], "role": role, "modules": {"project": project}, "is_super_admin": super_} return email def get(self, email: str): return self.d.get((email or "").lower()) def list_all(self): return list(self.d.values()) USERS = _Users() SENT_MAIL: list[dict] = [] if ENABLED: from fastapi.responses import HTMLResponse fake_main = types.ModuleType("app.main") fake_main.user_store = USERS def _current(request): return USERS.get(request.headers.get("x-test-user", "")) fake_main.get_current_user_record = _current fake_main.build_erp_nav = lambda user, active="": [] fake_main.render_template = lambda request, name, ctx, status_code=200: HTMLResponse( f"{name}|{ctx.get('reason', '')}", status_code=status_code) sys.modules["app.main"] = fake_main for k in list(os.environ): if k.startswith("SMTP_") or k == "PROJECT_NOTIFY_EMAIL": os.environ.pop(k) import app.mail as _mail # noqa: E402 _mail.send_email = lambda **kw: SENT_MAIL.append(kw) from fastapi import FastAPI # noqa: E402 from fastapi.testclient import TestClient # noqa: E402 from app.modules.project import reminders # noqa: E402 from app.modules.project import router as project_api_router # noqa: E402 - 패키지가 APIRouter 를 내보낸다 from app.modules.project.db import ProjectStore # noqa: E402 from app.timezone import today_kst # noqa: E402 ST = ProjectStore(DSN) DATA_DIR = tempfile.mkdtemp(prefix="pj-test-") APP = FastAPI() APP.include_router(project_api_router) APP.state.project_store = ST APP.state.data_dir = DATA_DIR CLIENT = TestClient(APP) RUN = uuid.uuid4().hex[:6] ADMIN = USERS.add(f"admin-{RUN}@test.local", role="admin") SUPER = USERS.add("king@dbxcorp.co.kr", role="admin", super_=True) ALICE = USERS.add(f"alice-{RUN}@test.local") BOB = USERS.add(f"bob-{RUN}@test.local") CAROL = USERS.add(f"carol-{RUN}@test.local") DAVE = USERS.add(f"dave-{RUN}@test.local") # 프로젝트 권한은 있으나 어디에도 멤버 아님 EVE = USERS.add(f"eve-{RUN}@test.local", project=False) # 프로젝트 모듈 권한 없음 def req(method: str, url: str, who: str, **kw): return CLIENT.request(method, url, headers={"x-test-user": who}, **kw) def _project(name: str, owner: str, members: tuple[str, ...] = ()) -> dict: p = ST.create_project(name=f"{name}-{uuid.uuid4().hex[:4]}", owner_email=owner, created_by=owner) for m in members: ST.add_member(project_id=p["id"], user_email=m) return p def _stage(pid: int, name: str = "할 일", done: bool = False, by: str = "") -> dict: return ST.add_stage(project_id=pid, name=name, is_done_stage=done, created_by=by) def _count(sql: str, *args) -> int: with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 전용 확인 쿼리 return int(conn.execute(sql, args).fetchone()["n"]) # ════════════════════════════════════════════════════════════ # [07] 소유자 변경은 관리자만 # ════════════════════════════════════════════════════════════ def test_owner_change_admin_only(): p = _project("P-owner", ADMIN, (BOB,)) r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": BOB}) assert r.status_code == 403, r.text assert ST.get_project(project_id=p["id"])["owner_email"] == ADMIN r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": CAROL, "name": "x"}) assert r.status_code == 403 and ST.get_project(project_id=p["id"])["name"] != "x" # 같은 값을 같이 보내는 건(화면 저장) 통과 assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200 # 관리자: 모듈 권한 없는 사람은 소유자 불가, 정상 사용자는 가능 assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": EVE}).status_code == 400 assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": CAROL}).status_code == 200 assert ST.get_project(project_id=p["id"])["owner_email"] == CAROL # 소유자에서 빠지면(관리자가 다시 바꿈) 멤버가 아닌 CAROL 은 관리 권한을 잃는다 assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": ADMIN}).status_code == 200 assert req("GET", f"/project/api/projects/{p['id']}/snapshot", CAROL).status_code == 403 # 생성: 비관리자가 남을 소유자로 지정 → 거절, 본인·미지정 → 본인이 소유자 assert req("POST", "/project/api/projects", BOB, json={"name": "n1", "owner_email": CAROL}).status_code == 403 r = req("POST", "/project/api/projects", BOB, json={"name": "n2"}) assert r.status_code == 201 and r.json()["project"]["owner_email"] == BOB # ════════════════════════════════════════════════════════════ # [06] 삭제 — 생성자 규칙 + 지금 권한 # ════════════════════════════════════════════════════════════ def test_delete_requires_current_access(): p = _project("P-del", ADMIN, (ALICE, BOB)) s = _stage(p["id"], by=ADMIN) t = req("POST", f"/project/api/projects/{p['id']}/tasks", ALICE, json={"title": "alice task", "stage_id": s["id"]}).json()["task"] ST.add_comment(task_id=t["id"], author_email=ALICE, author_name="a", body="hi") trash_before = _count("SELECT COUNT(*) AS n FROM project_trash") # 현재 멤버인 타인 → 생성자 규칙으로 거절 assert req("DELETE", f"/project/api/tasks/{t['id']}", BOB).status_code == 403 # 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음 ST.remove_member(project_id=p["id"], user_email=ALICE) assert req("DELETE", f"/project/api/tasks/{t['id']}", ALICE).status_code == 403 assert ST.get_task(task_id=t["id"]) is not None assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id = %s", t["id"]) == 1 assert _count("SELECT COUNT(*) AS n FROM project_trash") == trash_before # 다시 멤버가 된 생성자 → 삭제(휴지통) ST.add_member(project_id=p["id"], user_email=ALICE) r = req("DELETE", f"/project/api/tasks/{t['id']}", ALICE) assert r.status_code == 200 and ST.get_task(task_id=t["id"]) is None # 프로젝트 삭제: 만든 사람이어도 지금 권한이 없으면 거절, 슈퍼관리자는 예외 p2 = _project("P-del2", ALICE) ST.update_project(project_id=p2["id"], fields={"owner_email": ADMIN}) # 관리자가 소유자를 바꿈 assert req("DELETE", f"/project/api/projects/{p2['id']}", ALICE).status_code == 403 assert ST.get_project(project_id=p2["id"]) is not None assert req("DELETE", f"/project/api/projects/{p2['id']}", SUPER).status_code == 200 # ════════════════════════════════════════════════════════════ # [02] 권한 회수 후 조회·변경·알림 # ════════════════════════════════════════════════════════════ def test_revoked_member_loses_everything(): p = _project("P-rev", ADMIN, (ALICE, BOB)) s = _stage(p["id"], by=ADMIN) t = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "shared", "stage_id": s["id"], "assignee_email": ALICE, "description": f'@a'}).json()["task"] c = req("POST", f"/project/api/tasks/{t['id']}/comments", ALICE, json={"body": "mine"}).json()["comment"] assert any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"]) assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"]) assert any(n["task_id"] == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"]) ST.remove_member(project_id=p["id"], user_email=ALICE) assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"]) assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"]) assert not any(n.get("task_id") == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"]) for m, u, body in (("GET", f"/project/api/tasks/{t['id']}", None), ("GET", f"/project/api/tasks/{t['id']}/comments", None), ("GET", f"/project/api/tasks/{t['id']}/attachments", None), ("PUT", f"/project/api/tasks/{t['id']}", {"title": "x"}), ("PUT", f"/project/api/comments/{c['id']}", {"body": "edited"}), ("DELETE", f"/project/api/comments/{c['id']}", None), ("POST", f"/project/api/tasks/{t['id']}/followers", {})): r = req(m, u, ALICE, json=body) if body is not None else req(m, u, ALICE) assert r.status_code == 403, (m, u, r.status_code) assert ST.get_comment(comment_id=c["id"])["body"] == "mine" assert req("GET", f"/project/t/{t['id']}", ALICE, follow_redirects=False).status_code == 403 # 옛 공유 링크 # 완료 알림은 권한 잃은 담당자에게 가지 않는다(담당자 기록은 남음) before = _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"completed": True}).status_code == 200 assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) == before assert ST.get_task(task_id=t["id"])["assignee_email"] == ALICE # 권한 없는 사람을 새 담당자로 지정할 수 없다 assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"assignee_email": DAVE}).status_code == 400 # 관리자·owner·멤버는 그대로 assert req("GET", f"/project/api/tasks/{t['id']}", ADMIN).status_code == 200 assert req("GET", f"/project/api/tasks/{t['id']}", BOB).status_code == 200 # ════════════════════════════════════════════════════════════ # [08] 비멤버 @태그 # ════════════════════════════════════════════════════════════ def test_mentions_only_for_people_who_can_see(): p = _project("P-men", ADMIN, (BOB,)) s = _stage(p["id"], by=ADMIN) desc = "".join(f'@x' for e in (DAVE, EVE, "ghost@nowhere.test")) r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "m", "stage_id": s["id"], "description": desc}) t = r.json()["task"] assert set(r.json()["mention_skipped"]) == {DAVE, EVE, "ghost@nowhere.test"} assert _count("SELECT COUNT(*) AS n FROM task_mentions WHERE task_id=%s", t["id"]) == 0 r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@dave hi", "mentions": [DAVE]}) assert r.status_code == 201 and r.json()["mention_skipped"] == [DAVE] assert not req("GET", "/project/api/mentions", DAVE).json()["tasks"] or \ all(x["id"] != t["id"] for x in req("GET", "/project/api/mentions", DAVE).json()["tasks"]) # 멘션이 접근 권한을 만들지 않는다 assert req("GET", f"/project/api/tasks/{t['id']}", DAVE).status_code == 403 # 연결된 프로젝트 멤버는 태그 가능(읽기 권한) p2 = _project("P-men2", ADMIN, (BOB, CAROL)) s2 = _stage(p2["id"], by=ADMIN) assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": p2["id"], "stage_id": s2["id"]}).status_code == 201 r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@carol", "mentions": [CAROL]}) assert r.json()["mention_skipped"] == [] assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", CAROL).json()["tasks"]) # 태그 후보 API 도 같은 기준 cands = {u["email"] for u in req("GET", f"/project/api/all-users?task_id={t['id']}", BOB).json()["users"]} assert CAROL in cands and BOB in cands and DAVE not in cands and EVE not in cands # ════════════════════════════════════════════════════════════ # [12] 연결된 프로젝트 — 읽기 전용 # ════════════════════════════════════════════════════════════ def test_linked_task_is_read_only(): home = _project("P-home", ADMIN, (BOB,)) other = _project("P-link", ADMIN, (BOB, CAROL)) secret = _project("P-secret", ADMIN, (BOB,)) hs, os_ = _stage(home["id"], by=ADMIN), _stage(other["id"], by=ADMIN) os2 = _stage(other["id"], name="진행", by=ADMIN) ss = _stage(secret["id"], by=ADMIN) t = ST.create_task(project_id=home["id"], title="linked", stage_id=hs["id"], created_by=BOB) sib = ST.create_task(project_id=home["id"], title="sibling", stage_id=hs["id"], created_by=BOB) sub = ST.create_task(project_id=home["id"], title="child", parent_task_id=t["id"], created_by=BOB) for pid, sid in ((other["id"], os_["id"]), (secret["id"], ss["id"])): assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": pid, "stage_id": sid}).status_code == 201 r = req("GET", f"/project/api/tasks/{t['id']}", CAROL) assert r.status_code == 200 and r.json()["task"]["access"] == "read" assert [ln["project_id"] for ln in r.json()["task"]["links"]] == [other["id"]] # 비밀 프로젝트는 숨김 assert r.json()["task"]["followers"] is None assert req("GET", f"/project/api/tasks/{sub['id']}", CAROL).json()["task"]["access"] == "read" # 하위 작업도 읽기 assert req("GET", f"/project/api/tasks/{sib['id']}", CAROL).status_code == 403 # 원 소속의 다른 작업은 안 보임 assert req("GET", f"/project/api/projects/{home['id']}/members", CAROL).status_code == 403 assert req("GET", f"/project/api/tasks/{t['id']}/comments", CAROL).status_code == 200 for m, u, body in (("PUT", f"/project/api/tasks/{t['id']}", {"title": "hack"}), ("POST", f"/project/api/tasks/{t['id']}/comments", {"body": "hi"}), ("DELETE", f"/project/api/tasks/{t['id']}", None)): r = req(m, u, CAROL, json=body) if body is not None else req(m, u, CAROL) assert r.status_code == 403, (m, u, r.status_code) assert ST.get_task(task_id=t["id"])["title"] == "linked" # 연결된 프로젝트 안의 섹션 이동은 예전처럼 허용 assert req("POST", f"/project/api/tasks/{t['id']}/links", CAROL, json={"project_id": other["id"], "stage_id": os2["id"]}).status_code == 201 # 공유 링크 — 연결된 프로젝트 화면으로 r = req("GET", f"/project/t/{t['id']}", CAROL, follow_redirects=False) assert r.status_code == 303 and r.headers["location"] == f"/project/p/{other['id']}?task={t['id']}" # 전체 스냅샷에서 연결 행은 연결된 프로젝트 맥락으로 한 번씩(원 소속 행은 CAROL 에게 없음) snap = req("GET", f"/project/api/projects/{other['id']}/snapshot?scope=all", CAROL).json() rows = [x for x in snap["tasks"] if x["id"] == t["id"]] assert [(x["context_project_id"], x["is_linked"]) for x in rows] == [(other["id"], True)] # 연결 해제 후엔 볼 수 없다 assert req("DELETE", f"/project/api/tasks/{t['id']}/links/{other['id']}", BOB).status_code == 200 assert req("GET", f"/project/api/tasks/{t['id']}", CAROL).status_code == 403 # ════════════════════════════════════════════════════════════ # [03] 파일 댓글 — 원자적 등록·재전송 중복 방지 # ════════════════════════════════════════════════════════════ def test_file_comment_atomic_and_idempotent(): p = _project("P-file", ADMIN, (BOB, CAROL)) s = _stage(p["id"], by=ADMIN) t = ST.create_task(project_id=p["id"], title="files", stage_id=s["id"], created_by=BOB) url = f"/project/api/tasks/{t['id']}/comments/files" n0 = _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) # JSON 경로: 예전 has_attachment 플래그로 빈 댓글을 만들 수 없다 assert req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "", "has_attachment": True}).status_code == 400 # 한 파일이라도 문제면(빈 파일) 아무것도 만들지 않고 어느 파일인지 알려 준다 r = req("POST", url, BOB, files=[("files", ("ok.txt", b"hello", "text/plain")), ("files", ("empty.txt", b"", "text/plain"))]) assert r.status_code == 400 and [f["name"] for f in r.json()["detail"]["failed"]] == ["empty.txt"] assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 assert not os.path.isdir(os.path.join(DATA_DIR, "project", str(t["id"]))) or \ not os.listdir(os.path.join(DATA_DIR, "project", str(t["id"]))) # 정상: 본문 없이 파일 두 개, 같은 토큰으로 두 번 보내도 한 번만 files = [("files", ("a.png", b"\x89PNG....", "image/png")), ("files", ("b.pdf", b"%PDF-1", "application/pdf"))] r1 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files) r2 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files) assert r1.status_code == 201 and r2.status_code == 201 assert r1.json()["comment"]["id"] == r2.json()["comment"]["id"] and r2.json().get("duplicate") cid = r1.json()["comment"]["id"] assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1 assert _count("SELECT COUNT(*) AS n FROM task_attachments WHERE comment_id=%s", cid) == 2 # DB 저장 실패 → 방금 쓴 파일도 지우고 댓글 없음 orig = ST.add_comment_with_attachments ST.add_comment_with_attachments = lambda **kw: (_ for _ in ()).throw(RuntimeError("db down")) try: before_files = set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) try: req("POST", url, BOB, files=[("files", ("c.txt", b"data", "text/plain"))]) except RuntimeError: pass # TestClient 가 서버 예외를 그대로 올린다(운영에선 500) assert set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) == before_files finally: ST.add_comment_with_attachments = orig assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1 # 남의 댓글에 파일을 붙일 수 없다 r = req("POST", f"/project/api/tasks/{t['id']}/attachments", CAROL, data={"comment_id": str(cid)}, files={"file": ("x.txt", b"x", "text/plain")}) assert r.status_code == 403 # 동시에 같은 토큰 두 개 → 댓글 하나 out = [] ths = [threading.Thread(target=lambda: out.append(req("POST", url, BOB, data={"client_token": "tok-par"}, files=[("files", ("p.txt", b"p", "text/plain"))]).json())) for _ in range(2)] [th.start() for th in ths] [th.join() for th in ths] assert len({o["comment"]["id"] for o in out}) == 1 # ════════════════════════════════════════════════════════════ # [04] 날짜 범위 # ════════════════════════════════════════════════════════════ def test_date_range_validation(): p = _project("P-date", ADMIN, (BOB,)) s = _stage(p["id"], by=ADMIN) base = f"/project/api/projects/{p['id']}/tasks" assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400 t = req("POST", base, BOB, json={"title": "ok", "stage_id": s["id"], "start_date": "2026-10-01", "due_date": "2026-10-05"}).json()["task"] u = f"/project/api/tasks/{t['id']}" assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 400 # 한쪽만 바꿔도 최종 상태 검사 assert ST.get_task(task_id=t["id"])["due_date"] == "2026-10-05" assert req("PUT", u, BOB, json={"start_date": None}).status_code == 200 # null 로 지우기 assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 200 # 시작일 없으면 허용 assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400 assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200 assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200 # 프로젝트도 같은 규칙(부분 수정 포함) pu = f"/project/api/projects/{p['id']}" assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400 assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200 assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400 assert req("POST", "/project/api/projects", BOB, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400 # ════════════════════════════════════════════════════════════ # [11] 완료 섹션에 바로 만든 작업 # ════════════════════════════════════════════════════════════ def test_create_in_done_stage_completes(): p = _project("P-done", ADMIN, (ALICE, BOB)) todo, done = _stage(p["id"], by=ADMIN), _stage(p["id"], name="완료", done=True, by=ADMIN) SENT_MAIL.clear() r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "done now", "stage_id": done["id"], "assignee_email": ALICE}) t = r.json()["task"] assert t["completed_at"] and "_newly_completed" not in t assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='completed'", t["id"]) == 1 assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='completed' AND recipient_email=%s", t["id"], ALICE) == 1 # 일반 섹션 생성 → 미완료, 완료 섹션으로 이동 → 완료(이력 1건 더), 이탈 → 미완료 t2 = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "later", "stage_id": todo["id"]}).json()["task"] assert not t2["completed_at"] assert req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": done["id"]}).json()["task"]["completed_at"] assert not req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": todo["id"]}).json()["task"]["completed_at"] # 섹션 없는 하위 작업: 수동 완료/취소 sub = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "sub", "parent_task_id": t2["id"]}).json()["task"] assert sub["stage_id"] is None and not sub["completed_at"] assert req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": True}).json()["task"]["completed_at"] assert not req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": False}).json()["task"]["completed_at"] # ════════════════════════════════════════════════════════════ # [15] 마감 알림 — 원자적·재시도·중복 방지·권한 # ════════════════════════════════════════════════════════════ def test_due_reminders_atomic_and_access(): p = _project("P-rem", ADMIN, (ALICE, BOB)) s = _stage(p["id"], by=ADMIN) today = today_kst() t_ok = ST.create_task(project_id=p["id"], title=f"rem-ok-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB) t_gone = ST.create_task(project_id=p["id"], title=f"rem-gone-{RUN}", stage_id=s["id"], assignee_email=ALICE, due_date=today.isoformat(), created_by=BOB) t_fail = ST.create_task(project_id=p["id"], title=f"FAILME-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB) ST.remove_member(project_id=p["id"], user_email=ALICE) q = "SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='due_today'" qr = "SELECT COUNT(*) AS n FROM task_reminders WHERE task_id=%s" with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 DB 에서만: 알림 생성 실패 흉내 conn.execute(f"ALTER TABLE project_notifications ADD CONSTRAINT test_fail_{RUN} CHECK (title NOT LIKE '%%FAILME-{RUN}%%')") try: reminders.run_due_reminders(ST, today=today, lookup=USERS.get) assert _count(q, t_ok["id"]) == 1 and _count(q, t_gone["id"]) == 0 assert _count(q, t_fail["id"]) == 0 and _count(qr, t_fail["id"]) == 0 # 실패 → 기록도 되돌려짐 finally: with ST._pool.connection() as conn: # noqa: SLF001 conn.execute(f"ALTER TABLE project_notifications DROP CONSTRAINT test_fail_{RUN}") reminders.run_due_reminders(ST, today=today, lookup=USERS.get) # 재실행: 실패분만 생성 assert _count(q, t_fail["id"]) == 1 and _count(q, t_ok["id"]) == 1 # 동시 실행에도 중복 없음 t_par = ST.create_task(project_id=p["id"], title=f"rem-par-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB) ths = [threading.Thread(target=reminders.run_due_reminders, args=(ST,), kwargs={"today": today, "lookup": USERS.get}) for _ in range(4)] [th.start() for th in ths] [th.join() for th in ths] assert _count(q, t_par["id"]) == 1 assert _count(q, t_gone["id"]) == 0 and _count(qr, t_gone["id"]) == 0 # ════════════════════════════════════════════════════════════ # [01] 전체 범위 스냅샷 — 다른 프로젝트의 생성·삭제·섹션 변경·권한 회수 # ════════════════════════════════════════════════════════════ def test_snapshot_all_scope(): a = _project("P-sa", ADMIN, (BOB,)) b = _project("P-sb", ADMIN, (BOB,)) sa, sb = _stage(a["id"], by=ADMIN), _stage(b["id"], by=ADMIN) tb = ST.create_task(project_id=b["id"], title="in b", stage_id=sb["id"], created_by=BOB) snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json() assert {a["id"], b["id"]} <= {x["id"] for x in snap["projects"]} assert any(x["id"] == tb["id"] for x in snap["tasks"]) and str(b["id"]) in snap["stages_by_project"] sb2 = _stage(b["id"], name="new", by=ADMIN) ST.delete_task(task_id=tb["id"], deleted_by=BOB) snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json() assert not any(x["id"] == tb["id"] for x in snap["tasks"]) assert sb2["id"] in [s["id"] for s in snap["stages_by_project"][str(b["id"])]] ST.remove_member(project_id=b["id"], user_email=BOB) snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json() assert b["id"] not in {x["id"] for x in snap["projects"]} and str(b["id"]) not in snap["stages_by_project"] ST.remove_member(project_id=a["id"], user_email=BOB) assert req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).status_code == 403 _ = sa def test_store_date_range_unit(): from app.modules.project import store store.validate_date_range(None, "2026-01-01") store.validate_date_range("2026-01-01", None, "10:00", None) store.validate_date_range("2026-01-01", "2026-01-01", "23:59", None) for args in (("2026-01-02", "2026-01-01"), ("2026-01-01", "2026-01-01", "10:01", "10:00")): try: store.validate_date_range(*args) except ValueError: continue raise AssertionError(args) def test_store_goal_merge_unit(): from app.modules.project import store assert store.validate_goal_merge(3, 1) == (1, 3) assert store.validate_goal_merge(10, 12) == (10, 12) assert store.validate_goal_month(13, allow_year=True) == 13 assert store.validate_goal_month(16, allow_year=True) == 16 for bad in (17, -1): try: store.validate_goal_month(bad, allow_year=True) except ValueError: continue raise AssertionError(bad) # 분기를 넘는 병합(3~4월, 6~7월, 7~12월)은 거절 for args in ((3, 4), (6, 7), (7, 12), (3, 3), (0, 2), (11, 13)): try: store.validate_goal_merge(*args) except ValueError: continue raise AssertionError(args) def test_store_goal_quarters_unit(): """분기 칸(2026-10-01 상·하반기 → 1~4분기): 칸 순서·묶음·사각형 범위.""" from app.modules.project import store assert store.GOAL_COL_ORDER == (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16) assert [store.goal_quarter_of(m) for m in (1, 3, 4, 6, 7, 9, 10, 12)] == [1, 1, 2, 2, 3, 3, 4, 4] assert store.GOAL_QUARTER_COL == {1: 13, 2: 15, 3: 14, 4: 16} assert store.goal_col_group(13) == "q1" and store.goal_col_group(14) == "q3" assert store.goal_col_group(5) == store.goal_col_group(6) != store.goal_col_group(7) assert store.validate_goal_rect_cols(4, 6) == (4, 3) assert store.validate_goal_rect_cols(15, 15) == (15, 1) for a, b in ((3, 4), (3, 13), (6, 15), (0, 1)): try: store.validate_goal_rect_cols(a, b) except ValueError: continue raise AssertionError((a, b)) assert store.MEETING_TEMPLATE["마케팅"][0] == "메타" # ════════════════════════════════════════════════════════════ # 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기 # ════════════════════════════════════════════════════════════ def test_goal_cell_content_move(): """실제 PostgreSQL: 서식 포함 이동·동시 이동 충돌·권한·병합 가림·응답 유실 재시도.""" from app.modules.project import store year = 2060 + int(RUN, 16) % 40 assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 try: board = ST.get_goal_board(year=year) rid = board["areas"][0]["rows"][0]["id"] rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + '[{"text":"move","color":"#ff0000","size":24,"bold":true,"italic":true,"underline":true}]') ST.set_goal_cell(row_id=rid, month=1, body=rich) payload = {"source_row": rid, "source_month": 1, "target_row": rid, "target_month": 2, "source_body": rich, "target_body": "", "body": rich} endpoint = "/project/api/goals/cells/move" assert req("POST", endpoint, BOB, json=payload).status_code == 403 assert req("POST", endpoint, ADMIN, json=payload | {"target_month": 17}).status_code == 400 ST.set_goal_cell(row_id=rid, month=2, body="another edit") assert req("POST", endpoint, ADMIN, json=payload).status_code == 409 ST.set_goal_cell(row_id=rid, month=2, body="") assert req("POST", endpoint, ADMIN, json=payload).json() == {"ok": True, "body": rich} assert req("POST", endpoint, ADMIN, json=payload).status_code == 200 cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] assert 1 not in cells and cells[2] == rich # 같은 원본을 서로 다른 대상으로 동시에 이동하면 한 요청만 성공한다. ST.set_goal_cell(row_id=rid, month=1, body=rich) ST.set_goal_cell(row_id=rid, month=2, body="") barrier = threading.Barrier(2) results = [] def move_to(month): barrier.wait() try: ST.move_goal_cell(source_row=rid, source_month=1, target_row=rid, target_month=month, source_body=rich, target_body="", body=rich, updated_by=ADMIN) results.append("ok") except store.GoalCellConflict: results.append("conflict") workers = [threading.Thread(target=move_to, args=(m,)) for m in (2, 3)] for t in workers: t.start() for t in workers: t.join(timeout=10) assert sorted(results) == ["conflict", "ok"], results aid = board["areas"][0]["id"] ST.merge_goal_rect(area_id=aid, row_from=rid, row_to=rid, col_from=4, col_to=5) hidden = payload | {"source_month": 2 if 2 in ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] else 3, "target_month": 5} assert req("POST", endpoint, ADMIN, json=hidden).status_code == 409 finally: ST.delete_goal_year(year=year) def test_goal_halves_and_merges(): year = 2060 + int(RUN, 16) % 40 ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 try: board = ST.get_goal_board(year=year) assert board["halves"] is True, "마이그레이션 014 적용 필요" assert board["quarters"] is True, "마이그레이션 017 적용 필요" rid = board["areas"][0]["rows"][0]["id"] aid0 = board["areas"][0]["id"] cell = lambda m, body, who=ADMIN: req( # noqa: E731 "PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body}) # 분기 글 칸(13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기), 범위 밖(17)은 400, 비관리자는 403 for m, body in ((13, "1분기 글"), (15, "2분기 글"), (14, "3분기 글"), (16, "4분기 글")): assert cell(m, body).status_code == 200, m assert cell(17, "x").status_code == 400 assert cell(13, "y", BOB).status_code == 403 for m, body in ((2, "이월"), (3, "삼월")): assert cell(m, body).status_code == 200 merge = lambda s, e: req( # noqa: E731 — 엑셀식 병합 API(한 줄 가로) "POST", f"/project/api/goals/areas/{aid0}/merge", ADMIN, json={"row_from": rid, "row_to": rid, "col_from": s, "col_to": e}) # 분기를 넘는 병합(3~4월, 사이에 1분기 칸)·한 칸 병합은 400 assert merge(3, 4).status_code == 400 and merge(4, 4).status_code == 400 r = merge(2, 3) assert r.status_code == 200 and r.json() == {"ok": True, "row_id": rid, "start": 2, "span": 2, "row_span": 1}, r.text cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] assert cells[2] == "이월\n삼월" and 3 not in cells # 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만) assert cell(3, "늦은 저장").status_code == 400 # 걸친 병합은 흡수: 1~2 → 1~3, 글은 월 순서대로 이어진다 r = merge(1, 2) assert r.json() == {"ok": True, "row_id": rid, "start": 1, "span": 3, "row_span": 1}, r.text row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] assert row["merges"] == {1: (3, 1)} and row["cells"][1] == "이월\n삼월" and 2 not in row["cells"] assert row["cells"][13] == "1분기 글" and row["cells"][15] == "2분기 글" and row["cells"][16] == "4분기 글" # 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404 assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 200 assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 404 row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] assert row["merges"] == {} and row["cells"][1] == "이월\n삼월" # 로아스 % 표기(입력에 % 가 있어도 숫자로 저장) r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN, json={"metric": "roas", "kind": "target", "month": 1, "value": "499%"}) assert r.status_code == 200 and r.json()["label"] == "499%" and r.json()["value"] == 499 r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN, json={"metric": "sales", "kind": "target", "month": 1, "value": "1,200"}) assert r.json()["label"] == "1,200" # 영역·줄 이름(그 자리 수정이 쓰는 API) — 영역 이름은 빈 값 400, 줄 이름은 빈 값 허용 aid = ST.get_goal_board(year=year)["areas"][0]["id"] assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": ""}).status_code == 400 assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": "상품2"}).status_code == 200 assert req("PUT", f"/project/api/goals/rows/{rid}", ADMIN, json={"label": ""}).status_code == 200 # 줄 추가 — 기준 줄 위/아래(ref_row_id + place), 없으면 맨 끝. 다른 영역 줄 기준은 404, place 오류는 400 add = lambda body, who=ADMIN: req( # noqa: E731 "POST", f"/project/api/goals/areas/{aid}/rows", who, json=body) labels = lambda: [r["label"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731 before = labels() assert add({"label": "끝"}).status_code == 201 assert add({"label": "아래", "ref_row_id": rid, "place": "below"}).status_code == 201 assert add({"label": "위", "ref_row_id": rid, "place": "above"}).status_code == 201 assert labels() == ["위", before[0], "아래"] + before[1:] + ["끝"], labels() areas = ST.get_goal_board(year=year)["areas"] if len(areas) > 1: assert add({"label": "x", "ref_row_id": areas[1]["rows"][0]["id"]}).status_code == 404 assert add({"label": "x", "ref_row_id": rid, "place": "left"}).status_code == 400 assert add({"label": "x", "ref_row_id": "abc"}).status_code == 400 assert add({"label": "x"}, BOB).status_code == 403 finally: ST.delete_goal_year(year=year) # ════════════════════════════════════════════════════════════ # 연간 목표 — 엑셀식 사각형 병합 · 주간 회의록(마이그레이션 015) # ════════════════════════════════════════════════════════════ def test_goal_rect_merges(): """세로 병합(같은 영역 연속 줄)·연간/반기 칸 세로 병합, 걸친 병합 흡수, 가린 칸 저장 거절, 줄 끼우기/지우기에 따라 row_span 증감, 세로 병합에 걸린 줄 이동 거절, 다른 영역 줄 404.""" year = 2060 + (int(RUN, 16) + 7) % 40 ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 try: assert ST.get_goal_board(year=year)["rect"] is True, "마이그레이션 015 적용 필요" aid = ST.get_goal_board(year=year)["areas"][0]["id"] rows = lambda: ST.get_goal_board(year=year)["areas"][0]["rows"] # noqa: E731 while len(rows()) < 4: # 이전 연도 구조를 복사해 줄이 더 있을 수도 — 앞 4줄로 시험 req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json={"label": "채움"}) r1, r2, r3, r4 = [r["id"] for r in rows()][:4] put = lambda rid, m, body: req("PUT", f"/project/api/goals/rows/{rid}/cells/{m}", ADMIN, json={"body": body}) # noqa: E731 assert put(r1, 0, "연간1").status_code == 200 and put(r2, 0, "연간2").status_code == 200 assert put(r2, 4, "사월2").status_code == 200 merge = lambda a, b, c0, c1, who=ADMIN: req( # noqa: E731 "POST", f"/project/api/goals/areas/{aid}/merge", who, json={"row_from": a, "row_to": b, "col_from": c0, "col_to": c1}) # 연간 칸 세로 3줄 — 글은 위에서부터 이어 붙어 맨 위 칸에 r = merge(r1, r3, 0, 0) assert r.status_code == 200 and r.json() == {"ok": True, "row_id": r1, "start": 0, "span": 1, "row_span": 3}, r.text b = rows() assert b[0]["merges"] == {0: (1, 3)} and b[0]["cells"][0] == "연간1\n연간2" and 0 not in b[1]["cells"] assert put(r2, 0, "가린 칸").status_code == 400 # 가려진 칸 저장 거절 # 연간 + 1월 가로(묶음이 다름)·비관리자·다른 영역 줄 → 400·403·404 assert merge(r1, r1, 0, 1).status_code == 400 assert merge(r1, r2, 3, 4, BOB).status_code == 403 other = ST.get_goal_board(year=year)["areas"] if len(other) > 1: assert merge(r1, other[1]["rows"][0]["id"], 3, 3).status_code == 404 # 분기를 넘는 사각형(3~4월)은 400 assert merge(r1, r2, 3, 4).status_code == 400 # 사각형 2줄 × 2칸(4~5월) → 걸친 병합으로 넓히기: 5월 r2 ~ 6월 r3 → 4~6월 × r1~r3 assert merge(r1, r2, 4, 5).json()["row_span"] == 2 r = merge(r2, r3, 5, 6) assert r.json() == {"ok": True, "row_id": r1, "start": 4, "span": 3, "row_span": 3}, r.text assert rows()[0]["cells"].get(4) == "사월2" # 2분기 칸(15) 세로 병합(017) r = merge(r1, r2, 15, 15) assert r.status_code == 200 and r.json()["start"] == 15 and r.json()["row_span"] == 2, r.text assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/15", ADMIN).status_code == 200 # 세로 병합에 걸린 줄 이동 거절, 걸리지 않은 맨 아래 줄(r4)은 위로 못 감(r3 이 걸림) / 병합 해제 뒤엔 됨 assert req("POST", f"/project/api/goals/rows/{r2}/move", ADMIN, json={"direction": 1}).status_code == 400 assert req("POST", f"/project/api/goals/rows/{r4}/move", ADMIN, json={"direction": -1}).status_code == 400 # 병합 안쪽에 줄 끼우기 → row_span +1, 가려진 줄 지우기 → -1 assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json={"label": "끼움", "ref_row_id": r1, "place": "below"}).status_code == 201 assert rows()[0]["merges"] == {0: (1, 4), 4: (3, 4)} assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json={"label": "아래", "ref_row_id": r4, "place": "below"}).status_code == 201 assert rows()[0]["merges"] == {0: (1, 4), 4: (3, 4)} # 병합 밖이면 그대로 ins = rows()[1]["id"] assert req("DELETE", f"/project/api/goals/rows/{ins}", ADMIN).status_code == 200 assert rows()[0]["merges"] == {0: (1, 3), 4: (3, 3)} # 해제 — 글은 왼쪽 위 칸에 assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/0", ADMIN).status_code == 200 b = rows() assert b[0]["merges"] == {4: (3, 3)} and b[0]["cells"][0] == "연간1\n연간2" assert put(r2, 0, "이제 됨").status_code == 200 finally: ST.delete_goal_year(year=year) def test_goal_label_groups(): """항목 칸(2열) 묶음(016): 3열 추가(same_label) 아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이 첫 줄(이름 넘겨받음), 묶음 첫 줄 삭제 → 다음 줄이 첫 줄(이름 넘겨받음), 묶인 줄 이동 400, 항목 칸 나누기, 새 연도 복사에 묶음 유지.""" year = 2060 + (int(RUN, 16) + 13) % 40 for y in (year, year + 1): ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 try: assert ST.get_goal_board(year=year)["groups"] is True, "마이그레이션 016 적용 필요" aid = ST.get_goal_board(year=year)["areas"][0]["id"] rows = lambda: [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731 ids = lambda: [r["id"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731 first = ids()[0] assert req("PUT", f"/project/api/goals/rows/{first}", ADMIN, json={"label": "마케팅1"}).status_code == 200 add = lambda body: req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json=body) # noqa: E731 assert add({"ref_row_id": first, "place": "below", "same_label": True}).status_code == 201 assert rows()[:2] == [("마케팅1", False), ("", True)] # 같은 항목 칸 위(첫 줄 위) — 새 줄이 첫 줄, 이름을 넘겨받고 예전 첫 줄은 이어 붙음 r = add({"ref_row_id": first, "place": "above", "same_label": True}) assert r.status_code == 201 assert rows()[:3] == [("마케팅1", False), ("", True), ("", True)], rows() assert ids()[1] == first assert add({"same_label": True}).status_code == 400 # 기준 줄 없음 # 묶인 줄 이동 거절 assert req("POST", f"/project/api/goals/rows/{first}/move", ADMIN, json={"direction": 1}).status_code == 400 # 묶음 첫 줄 삭제 → 다음 줄이 첫 줄 + 이름 head = ids()[0] assert req("DELETE", f"/project/api/goals/rows/{head}", ADMIN).status_code == 200 assert rows()[:2] == [("마케팅1", False), ("", True)], rows() # 새 연도 복사 — 묶음 유지 assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year + 1}).status_code == 201 nxt = [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year + 1)["areas"][0]["rows"]] assert nxt[:2] == [("마케팅1", False), ("", True)], nxt # 항목 칸 나누기 r = req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", ADMIN) assert r.status_code == 200 and r.json()["split"] == 1 assert rows()[:2] == [("마케팅1", False), ("", False)] assert req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", BOB).status_code == 403 finally: for y in (year, year + 1): ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None def test_goal_meetings(): """주간 회의록: 만들기(처음 = 목표 표 영역 + 기본 양식 줄, 유통 줄 쇼핑몰 추측), 다음 주 = 지난 회의록 줄 이어받기 (carry_from → prev), 금액 표기(만·억), 평가 값 검사, 줄 추가/이동/삭제, 화면·권한.""" base = date(2001, 1, 1) + timedelta(days=7 * (int(RUN, 16) % 400)) # 월요일(앞선 회의록이 없을 먼 과거) assert base.weekday() == 0 w1, w2 = base, base + timedelta(days=7) for w in (w2, w1): try: ST.delete_meeting(week_start=w) except KeyError: pass try: assert req("POST", f"/project/api/goals/meetings/{w1}", BOB, json={"year": w1.year}).status_code == 403 assert req("POST", f"/project/api/goals/meetings/{w1 + timedelta(days=1)}", ADMIN, json={}).status_code == 400 r = req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year}) assert r.status_code == 201 and r.json()["created"] is True, r.text assert req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year}).json()["created"] is False m1 = ST.get_meeting(week_start=w1) secs = [s for s in dict.fromkeys(it["section"] for it in m1["items"])] assert secs[:4] == ["상품", "마케팅", "컨텐츠", "유통"], secs coupang = next(it for it in m1["items"] if it["section"] == "유통" and it["label"] == "쿠팡") assert coupang["marketplace_code"] == "coupang" assert next(it for it in m1["items"] if it["section"] == "마케팅" and it["label"] == "네이버")["marketplace_code"] == "" put = lambda iid, body, who=ADMIN: req("PUT", f"/project/api/goals/meeting-items/{iid}", who, json=body) # noqa: E731 r = put(coupang["id"], {"content": "추석 타임딜", "target_amount": "1,200만"}) assert r.status_code == 200 and r.json()["item"]["target_amount"] == 12_000_000, r.text assert put(coupang["id"], {"target_amount": "abc"}).status_code == 400 assert put(coupang["id"], {"status": "bogus"}).status_code == 400 assert put(coupang["id"], {"content": "x"}, BOB).status_code == 403 assert req("PUT", f"/project/api/goals/meetings/{w1}", ADMIN, json={"week_target": "3천만", "attendees": "대표", "notes": "메모"}).status_code == 200 # 다음 주 — 줄을 이어받고 전주 칸(prev)에 지난주 할 일·목표 assert req("POST", f"/project/api/goals/meetings/{w2}", ADMIN, json={"year": w2.year}).status_code == 201 m2 = ST.get_meeting(week_start=w2) assert len(m2["items"]) == len(m1["items"]) and all(it["content"] == "" for it in m2["items"]) c2 = next(it for it in m2["items"] if it["carry_from"] == coupang["id"]) assert c2["prev"]["content"] == "추석 타임딜" and c2["prev"]["target_amount"] == 12_000_000 assert m2["prev_meeting"] == {"week_start": w1.isoformat(), "week_target": 30_000_000} # 지난주 결과·평가는 지난 회의록 줄에 저장 assert put(coupang["id"], {"result_amount": "1.5억", "status": "done"}).json()["item"]["result_amount"] == 150_000_000 # 줄 추가(기준 줄 아래)·이동(같은 구역 안)·삭제, 새 구역 r = req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN, json={"section": "유통", "label": "롯데온", "ref_item_id": c2["id"], "place": "below"}) assert r.status_code == 201, r.text new_id = r.json()["id"] labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]] assert labels[labels.index("쿠팡") + 1] == "롯데온" assert next(it for it in ST.get_meeting(week_start=w2)["items"] if it["id"] == new_id)["marketplace_code"] == "lotteon" assert req("POST", f"/project/api/goals/meeting-items/{new_id}/move", ADMIN, json={"direction": -1}).status_code == 200 labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]] assert labels.index("롯데온") < labels.index("쿠팡") assert req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN, json={"section": "물류"}).status_code == 201 assert ST.get_meeting(week_start=w2)["items"][-1]["section"] == "물류" assert req("DELETE", f"/project/api/goals/meeting-items/{new_id}", ADMIN).status_code == 200 # 화면 — 그 달 주차 탭, 회의록 줄 page = req("GET", f"/project/goals/{w2.year}/meetings/{w2.month}?week={w2}", BOB) assert page.status_code == 200 and page.text.startswith("project/goal_meeting.html"), page.text v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", BOB) assert v.status_code == 200 and v.json()["meeting"]["week_start"] == w2.isoformat() # 지난 회의록을 지우면 다음 주 전주 칸은 비고(carry_from NULL), 회의록은 남는다 assert req("DELETE", f"/project/api/goals/meetings/{w1}", ADMIN).status_code == 200 assert all(it["prev"] is None for it in ST.get_meeting(week_start=w2)["items"]) finally: for w in (w2, w1): try: ST.delete_meeting(week_start=w) except KeyError: pass def _meet_weeks(seed: int, n: int) -> list[date]: """지난 주들(실적 기간이 "진행 전"이 아니게) — test_goal_meetings(2001~2008)와 겹치지 않는 2010~2018 의 월요일 n 개.""" base = date(2010, 1, 4) + timedelta(days=7 * ((int(RUN, 16) + seed * 60) % 400)) assert base.weekday() == 0 return [base + timedelta(days=7 * i) for i in range(n)] def _drop_meetings(weeks: list[date]) -> None: for w in weeks: try: ST.delete_meeting(week_start=w) except KeyError: pass def _create_meeting(w: date) -> None: r = req("POST", f"/project/api/goals/meetings/{w}", ADMIN, json={"year": w.year}) assert r.status_code == 201, r.text # ════════════════════════════════════════════════════════════ # [G4·G5] 회의록 "지난주" — 정확히 7일 전 주, 생성 순서·이름 변경·같은 이름·삭제/재생성과 무관(018 line_key) # ════════════════════════════════════════════════════════════ def test_meeting_prev_week_links(): """지난주 = 정확히 7일 전 주 회의록의 같은 연결키 줄. 018 미적용이면 carry_from 이 7일 전 주일 때만.""" w0, w1, w2, w3 = _meet_weeks(1, 4) _drop_meetings([w0, w1, w2, w3]) with ST._pool.connection() as conn: # noqa: SLF001 keyed = ST._meeting_keys(conn) # noqa: SLF001 print(" meeting line_key(018):", "applied" if keyed else "not applied — carry_from fallback") try: # ① 역순 생성 — 다음 주(w3)를 먼저(양식), 앞 주(w2)를 나중에 _create_meeting(w3) _create_meeting(w2) m3 = ST.get_meeting(week_start=w3) assert m3["prev_meeting"] is not None and m3["prev_meeting"]["week_start"] == w2.isoformat() if keyed: assert all(it["prev"] is not None for it in m3["items"]), "역순 생성인데 지난주 줄이 빠짐" for it in m3["items"]: assert it["prev"]["week_start"] == w2.isoformat() assert (it["prev"]["section"], it["prev"]["label"]) == (it["section"], it["label"]) # 다른 구역의 같은 이름(마케팅 "네이버" ↔ 유통 "네이버")이 섞이지 않는다 navers = [it for it in m3["items"] if it["label"] == "네이버"] assert len(navers) == 2 and len({it["prev"]["id"] for it in navers}) == 2 assert all(it["prev"]["section"] == it["section"] for it in navers) else: assert all(it["prev"] is None for it in m3["items"]), "018 미적용 — 역순 생성 연결은 안 됨(문서화된 제한)" # ② 지난주(w2) 결과를 w2 줄에 저장 → w3 화면에서 보인다(그 주 데이터만) m2 = ST.get_meeting(week_start=w2) cou2 = next(it for it in m2["items"] if it["section"] == "유통" and it["label"] == "쿠팡") assert req("PUT", f"/project/api/goals/meeting-items/{cou2['id']}", ADMIN, json={"content": "w2 쿠팡 행사", "target_amount": "100", "result_amount": "50"}).status_code == 200 cou3 = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["section"] == "유통" and it["label"] == "쿠팡") if keyed: assert cou3["prev"]["id"] == cou2["id"] and cou3["prev"]["content"] == "w2 쿠팡 행사" # ③ 이름 변경·순서 이동에도 연결 유지 assert req("PUT", f"/project/api/goals/meeting-items/{cou3['id']}", ADMIN, json={"label": "쿠팡 로켓"}).status_code == 200 assert req("POST", f"/project/api/goals/meeting-items/{cou3['id']}/move", ADMIN, json={"direction": -1}).status_code == 200 again = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["id"] == cou3["id"]) assert again["prev"]["id"] == cou2["id"] # ④ 같은 이름의 새 줄은 지난주와 연결되지 않고, 기존 줄 연결도 그대로 r = req("POST", f"/project/api/goals/meetings/{w3}/items", ADMIN, json={"section": "유통", "label": "쿠팡", "ref_item_id": cou3["id"], "place": "below"}) new_id = r.json()["id"] items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]} assert items3[new_id]["prev"] is None and items3[cou3["id"]]["prev"]["id"] == cou2["id"] # ⑤ 앞 주 삭제 → 지난주 칸 빔, 다시 만들면(앞선 회의록 없음 → 다음 주 w3 양식·키) 다시 연결 ST.delete_meeting(week_start=w2) assert all(it["prev"] is None for it in ST.get_meeting(week_start=w3)["items"]) _create_meeting(w2) items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]} assert items3[cou3["id"]]["prev"] is not None and items3[cou3["id"]]["prev"]["week_start"] == w2.isoformat() assert items3[cou3["id"]]["prev"]["content"] == "" # 새 회의록 — 예전 글이 섞이지 않는다 # ⑥ 한 주 건너뜀 — w0 를 만들고 w1 없이 w2 를 보면 지난주(w1) 자료 없음(w0 결과를 지난주로 보이지 않음) _drop_meetings([w2, w3]) _create_meeting(w0) cou0 = next(it for it in ST.get_meeting(week_start=w0)["items"] if it["section"] == "유통" and it["label"] == "쿠팡") req("PUT", f"/project/api/goals/meeting-items/{cou0['id']}", ADMIN, json={"target_amount": "100", "result_amount": "50"}) _create_meeting(w2) m2 = ST.get_meeting(week_start=w2) assert m2["prev_meeting"] is None and all(it["prev"] is None for it in m2["items"]) v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json() assert v["head"]["prev_exists"] is False and v["head"]["prev_target"] is None assert all(it["rate"] is None for it in v["meeting"]["items"]) # w1 을 만들면 w2 의 지난주 = w1(그 주 줄, 비어 있음) — w0 의 50/100 이 아니다 _create_meeting(w1) v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json() assert v["head"]["prev_exists"] is True prevs = [it["prev"] for it in v["meeting"]["items"] if it["prev"]] if keyed: assert prevs and all(p["week_start"] == w1.isoformat() for p in prevs) assert all(p["week_start"] == w1.isoformat() for p in prevs) assert all(it["rate"] is None for it in v["meeting"]["items"]) finally: _drop_meetings([w0, w1, w2, w3]) # ════════════════════════════════════════════════════════════ # [G6] 실적 조회 장애 ≠ 0원 — 목록 장애·매출 조회 장애·부분 실패·정상 0건·미연결·집계 쇼핑몰 없음 # ════════════════════════════════════════════════════════════ class _FakePerf: def __init__(self, *, list_error=False, sales_error=None, markets=None, amounts=None): self.list_error, self.sales_error = list_error, sales_error or (lambda a, b: False) self.markets = markets if markets is not None else [ {"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True}] self.amounts = amounts or {} self.calls = [] def list_marketplaces(self): if self.list_error: raise RuntimeError("perf db down") return self.markets def daily_amounts(self, start, end, codes): self.calls.append((start, end)) if self.sales_error(start, end): raise RuntimeError("sales query failed") return {(d, c): v for (d, c), v in self.amounts.items() if start <= d <= end and c in codes} def statuses(self): return {"coupang": {"last_success_sync_at": "2026-10-01T14:20:00+09:00"}} def test_meeting_perf_unknown_vs_zero(): """실적 모듈 장애는 미확인(None + head.unknown), 정상 무매출만 0. 의존하는 필요 매출·달성률도 미확인.""" from app.modules.project import store (w,) = _meet_weeks(2, 1) # 그 달 셋째 주 — 월 누적(1일~지난주 일요일)과 전주 결과(지난주 월~일) 조회 기간이 서로 다르게 weeks = store.month_weeks(w.year, w.month) w = weeks[2][0] month_first = date(w.year, w.month, 1) _drop_meetings([w, w - timedelta(days=7)]) orig_targets = ST.goal_month_targets ST.goal_month_targets = lambda **kw: {"sales_unit": "원", "sales_target": 1000.0, "sales_actual": None, "roas_target": None} try: _create_meeting(w - timedelta(days=7)) _create_meeting(w) prev = ST.get_meeting(week_start=w - timedelta(days=7)) cou_prev = next(it for it in prev["items"] if it["label"] == "쿠팡") req("PUT", f"/project/api/goals/meeting-items/{cou_prev['id']}", ADMIN, json={"target_amount": "100"}) url = f"/project/api/goals/meetings/{w}?year={w.year}&month={w.month}" def view(perf): APP.state.performance_store = perf try: r = req("GET", url, ADMIN) assert r.status_code == 200, r.text return r.json() finally: APP.state.performance_store = None def coupang_row(v): return next(it for it in v["meeting"]["items"] if it["label"] == "쿠팡" and it["section"] == "유통") # 실적 모듈 미연결 — perf False, 값 없음(미확인 아님) v = view(None) assert v["head"]["perf"] is False and v["head"]["perf_state"] == "off" and v["head"]["unknown"] == [] # 쇼핑몰 목록 장애 — 0 이 아니라 미확인, 필요 매출도 계산하지 않음, 회의록은 열림 v = view(_FakePerf(list_error=True)) h = v["head"] assert h["perf"] is True and h["perf_state"] == "error" assert h["mtd"] is None and h["prev_result"] is None and h["need_per_week"] is None assert {"mtd", "prev_result"} <= set(h["unknown"]), h row = coupang_row(v) assert row["prev"]["auto_error"] is True and row["prev"]["result"] is None and row["rate"] is None assert row["market_unknown"] is True and row["market_off"] is False assert v["markets"] == [] # 매출 조회 장애(목록은 정상) — 전부 미확인 v = view(_FakePerf(sales_error=lambda a, b: True)) h = v["head"] assert h["perf_state"] == "ok" and h["mtd"] is None and h["need_per_week"] is None assert {"mtd", "prev_result"} <= set(h["unknown"]) assert coupang_row(v)["prev"]["auto_error"] is True and coupang_row(v)["rate"] is None # 정상 조회 0 건 — 진짜 0원(미확인 아님), 필요 매출 = 목표 ÷ 남은 주 v = view(_FakePerf()) h = v["head"] assert h["mtd"] == 0 and h["prev_result"] == 0 and h["unknown"] == [], h assert h["need_per_week"] == 1000 // h["weeks_left"] row = coupang_row(v) assert row["prev"]["auto_result"] == 0 and row["prev"]["auto_error"] is False and row["rate"] == 0.0 assert h["fresh_oldest"] == "10/01 14:20" and "쿠팡 10/01 14:20" in h["fresh_tip"] # 부분 실패 — 월 누적(1일부터) 조회만 실패: 누적·필요 매출만 미확인, 전주 결과·줄 결과는 정상 prev_start = w - timedelta(days=7) v = view(_FakePerf(sales_error=lambda a, b: a == month_first and a != prev_start, amounts={(prev_start, "coupang"): 70})) h = v["head"] assert "mtd" in h["unknown"] and "prev_result" not in h["unknown"], h assert h["mtd"] is None and h["need_per_week"] is None and h["prev_result"] == 70 assert coupang_row(v)["prev"]["auto_result"] == 70 and coupang_row(v)["rate"] == 70.0 # 매출 집계 쇼핑몰 없음 — 0 원으로 보이지 않게(empty, 미확인도 아님) v = view(_FakePerf(markets=[{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": False}])) assert v["head"]["perf_state"] == "empty" and v["head"]["mtd"] is None and v["head"]["unknown"] == [] # 금주 목표 저장 응답 = 서버 확정값(원 정수) r = req("PUT", f"/project/api/goals/meetings/{w}", ADMIN, json={"week_target": "120만"}) assert r.status_code == 200 and r.json()["week_target"] == 1_200_000 finally: ST.goal_month_targets = orig_targets _drop_meetings([w, w - timedelta(days=7)]) if __name__ == "__main__": if not ENABLED: print("SKIP: PROJECT_TEST_DB_URL(localhost) not set") sys.exit(0) n = 0 for name, fn in sorted(globals().items()): if name.startswith("test_") and callable(fn): fn() n += 1 print("ok", name) print(f"{n} tests passed") ST.close() _ = io, timedelta